Search code examples
jsontypescriptgraphqlgatsby

How do I fetch data from a local JSON file in Gatsby using TypeScript and GraphQL?


I'm recreating my old gatsby side using TypeScript. I get this error when I want to get data from local json file:

There was an error in your GraphQL query:

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

If you don't expect "allNavigationLinksJson" to exist on the type "Query" it is most likely a typo. However, if you expect "allNavigationLinksJson" to exist there are a couple of solutions to common problems:

- If you added a new data source and/or changed something inside gatsby-node/gatsby-config, please try a restart of your development server.
- You want to optionally use your field "allNavigationLinksJson" and right now it is not used anywhere.

It is recommended to explicitly type your GraphQL schema if you want to use optional fields.

My structure is:

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

navigation.json

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

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;

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/`,
        },
    },
\],
};\`

Can someone please explain me how does fetching data from local file work in gatbys + typescript?

I checked ___graphql it doesn't contain allNavigationLinksJson. I wrote types for query. I configured gatsby-config few times. I cleaned cache nothing seems to work. When I run gatsby serve I got error with gatsby-config.ts can be converted to gatsby-config.js. But I'm not sure if this error is result of my query or is reason why my query is not working.


Solution

  • There are several things that are noticeable:

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

    1. Try cleaning up the file and see if the conversion error to gatsby-config.js you got goes away. If you are not using it already, try to use an IDE like VSCode to spot these errors early on.
    2. The file you have your data in is called "navigation.json", with the gatsby-transformer-json plugin, the resulting graphql query would be AllNavigationJson not AllNavigationLinksJson.
    3. You might need to remove the trailing comma in navigation.json, not sure if it will be parsed correctly otherwise.

    (This is not necessarily a full answer, but since I cannot comment yet I posted it as one.)