What is the best way to access data from a local JSON file in Gatsby when using TypeScript and GraphQL?

I'm updating my former gatsby site using TypeScript. I encountered an issue while trying to retrieve data from a local JSON file:

There appears to be an error in your GraphQL query:

Cannot find field "allNavigationLinksJson" on type "Query".

If you believe that "allNavigationLinksJson" should exist within the type "Query," there are a few solutions to common problems:

- If you recently added a new data source or made changes in gatsby-node/gatsby-config, try restarting your development server.
- You may need to explicitly define your GraphQL schema if you intend to use optional fields like "allNavigationLinksJson."

It is recommended to specify your GraphQL schema for optional fields.

This is the structure:

\--data  
\----navigation.json  
\--src

The contents of navigation.json:

[{"title": "Home","href": "/"},]

The code from index.tsx:

import * as React from 'react';
import {
    CreateSchemaCustomizationArgs,
    HeadFC,
    PageProps,
    graphql,
    useStaticQuery
} from 'gatsby';
import { Footer } from '../components/layout';

type DataProps = {
    href: string;
    title: string;
    id: string;
};

const data = useStaticQuery(graphql
    query NavQuery {
        allNavigationLinksJson {edges {
            node {
               href
               title
               id
             }
           }
         }
      }
);
const IndexPage = ({ data: { title } }: PageProps<DataProps>) =>
{
return (
    <main>{title}</main>
);};

export default IndexPage;

Contents of gatsby-config.ts:


import type { GatsbyConfig } from 'gatsby';

const config: GatsbyConfig = {
    siteMetadata: {
    title: `Test page`,
    description: 'This is descrioption',
    siteUrl: `https://test.test`,
    author: 'me',
},
graphqlTypegen: true,
plugins: \[
    'gatsby-plugin-offline',
    'gatsby-plugin-react-helmet',
    'gatsby-plugin-image',
    'gatsby-plugin-sharp',
    'gatsby-transformer-sharp',
    'gatsby-plugin-sitemap',
    'gatsby-plugin-breakpoints',
    'gatsby-transformer-json',
    {
        resolve: 'gatsby-plugin-manifest',
        options: {
            icon: 'src/images/icon.png',
        },
    },
    {
        resolve: 'gatsby-plugin-anchor-links',
        options: {
            offset: -100,
            duration: 1000,
        },
    },
    {
        resolve: 'gatsby-plugin-postcss',
        options: {
            postCssPlugins: \[
                require('postcss-preset-env')({ stage: 0 }),
                require('postcss-nested'),
            \],
        },
    },
    {
        resolve: 'gatsby-source-filesystem',
        options: {
            name: 'projects',`your text`
            path: `${__dirname}/src/content/projects/`,
        },
    },
    {
        resolve: 'gatsby-source-filesystem',
        options: {
            name: 'navigation',
            path: `${__dirname}/data/`,
        },
    },
\],
};\`

I would appreciate any guidance on fetching data from a local file in Gatsby + TypeScript.

I have checked ___graphql but it does not contain allNavigationLinksJson. I have written types for the query and configured gatsby-config multiple times. Clearing cache did not solve the issue either. Upon running gatsby serve, I receive an error regarding gatsby-config.ts potentially needing conversion to gatsby-config.js. I am unsure whether this error is related to my query problem or is causing my query to fail.

Answer №1

Upon examination, it is apparent that there are several notable observations:

The gatsby-config.ts file you provided is not a valid TypeScript file. It contains multiple backslashes and some your text inserted in the middle of your code.

  1. I recommend tidying up the file to see if this resolves the conversion error to gatsby-config.js. Additionally, consider utilizing an IDE like VSCode to identify these types of errors early on.
  2. It seems that the data file you are using is named "navigation.json". With the gatsby-transformer-json plugin, the appropriate GraphQL query would be AllNavigationJson, rather than AllNavigationLinksJson.
  3. You may need to eliminate the trailing comma in navigation.json, as it may affect the parsing process if left unaddressed.

(Please note that this response does not offer a comprehensive solution, but due to commenting restrictions, I have posted it as an answer instead.)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to extract the value from a switchMap observable instead of just receiving the observable itself?

I am currently working on creating a unique in-memory singleton that stores the vendor being viewed by a user. A guard is implemented on all specific routes to capture the parameter: canActivate( route: ActivatedRouteSnapshot, state: RouterStateSnapsh ...

How to display an [object HTMLElement] using Angular

Imagine you have a dynamically created variable in HTML and you want to print it out with the new HTML syntax. However, you are unsure of how to do so. If you tried printing the variable directly in the HTML, it would simply display as text. This is the ...

Differences between Angular 4 and AngularJs directives

Delving into the world of Angular 4, I have encountered a slight hurdle in my understanding of directives. My goal is to create a directive that can resize an element based on its width. Back in the days of AngularJs, this task was accomplished with code r ...

Struggling to set up gatsby.js, encountering numerous error messages

When attempting to globally install gatsby-cli, the following error occurs: Could this be a permission problem? Or did I overlook something? npm WARN deprecated [email protected]: core-js@<3.0 is no longer maintained and not recommended for usa ...

Guide for choosing the appropriate VM T-shirt size within the Azure ARM Template

I am utilizing a VM deployment template where I specify the VM size using T-Shirt Sizes, for example, small = Standard_DS2_v2, medium = Standard_E4s_v3 and large = Standard_E32s_v3. These sizes are defined in an array within the variables section as shown ...

Updating the React State is dependent on the presence of a useless state variable in addition to the necessary state variable being set

In my current setup, the state is structured as follows: const [items, setItems] = useState([] as CartItemType[]); const [id, setId] = useState<number | undefined>(); The id variable seems unnecessary in this context and serves no purpose in my appl ...

Creating a Breeze js entity using a JSON string and importing it into the breeze cache: A step-by-step guide

Currently, I am developing a mobile single page website that utilizes technologies like breeze js, angular js, web API, and entity framework. To enhance the performance of the site, I have decided to include the breeze metadata in a bundled JavaScript fil ...

Mutations are not set up in the schema

Having an issue with setting up mutations in my project using npm, apollo server, and typeorm. Every time I attempt to create a mutation, I receive the error message "Schema is not configured for mutations". Searching for solutions has been fruitless as mo ...

Troubleshooting: The issue with json_encode in Ajax calls

I am facing an issue with my ajax call and the json response. The console is indicating that my php file is not returning a json format, but I am unable to pinpoint the exact reason behind it. Below is my ajax function: function showEspece(espece, categori ...

Utilizing AJAX to retrieve and process JSON information

Hey there! I've been diving into the world of creating AJAX calls to PHP scripts lately. Trying to figure out the best solution to handle these AJAX calls, you can check out my client-side code in this question. I'm here to validate my underst ...

Exploring the Relationship Between jQuery and JSON through Iterating Over JSON Arrays

There is an array stored in a database: a:4:{i:1;s:4:"1993";i:2;s:4:"1994";i:3;s:4:"1995";i:4;s:4:"1996";} To manipulate this array, I first unserialize it using PHP and then encode it with JSON. The code snippet is as follows: $unwp = unserialize(&apos ...

I'm curious, can you combine two fields when indexing JSON in Solr using an update request?

Currently, I am exploring the use of cURL to index JSON files and have a question regarding how to concatenate two fields while indexing JSON data. In the Solr documentation, there is an example that demonstrates this: curl 'http://localhost:8983/solr ...

The issue arises when TypeScript is unable to accurately infer the type as not being undefined following a type guard condition using

The following code snippet illustrates that in the else statement, it is evident that b cannot be undefined (a||b returns truthy and since a is falsy, b must be truthy). Why does Typescript show the error 'b' is possibly 'undefined', a ...

Limit an object to only contain interface properties

Suppose we have the following object: o {a : 1, b : 2} and this interface defined as: interface MyInterface { a : number } We are now looking to create a new object that represents the "intersection" of o and the MyInterface: o2 : {a : 1} The mai ...

Unable to make changes to the AWS Dynamo array

I am currently attempting to update a JSON array. I have a table in DynamoDB where I successfully inserted the JSON data using the PUT method. Partition key : _id , Type : S Below is the JSON data that has been saved into the database: { "_id": ...

Issue with the code flow causing nested function calls to not work as expected

I'm experiencing an issue with my code: The problem arises when param.qtamodificata is set to true, causing the code to return "undefined" due to asynchronous calls. However, everything works fine if params.qtamodificata is false. I am seeking a sol ...

Google Feed API - Retrieving saved data from RSS feed cache

We have implemented the Google Feed API to display our latest blog posts on our website. However, even after 24 hours, our most recent post is still not appearing on our site. Despite confirming that the RSS feed contains the newest content, it seems that ...

Retrieving selected item values in Angular 2 using ng2-completer

Recently, I decided to experiment with a new autocompleter tool that is unfamiliar to me: https://github.com/oferh/ng2-completer. I successfully imported it and it seems to be functioning properly. My current goal is to retrieve the values of the selecte ...

Attention: issue TS18002 has been detected - The 'files' configuration file is currently blank

I'm currently working with TypeScript version 2.1.5.0. My setup includes the grunt-typescript-using-tsconfig plugin, but I'm encountering an error when running the task. The issue seems to be related to the property "files":[] in my tsconfig.jso ...

What could be the reason behind the login button not triggering the console message display?

I've decided to delve into web server development on my own and have been tweaking a GitHub repository for ExpressJS with Typescript that I stumbled upon. My initial goal is simple - just to have something displayed on the console when I click the log ...