Home > Enterprise >  Try to catch nodes info from with useStaticQuery of Gatsby
Try to catch nodes info from with useStaticQuery of Gatsby

Time:01-14

I'm trying to catch info from GraphQL Gatsby with useStaticQuery but the data returned is undefined and I don't understand why because in my http://localhost:8000/___graphql I received the good information.

My code is not a page component it's a reason why I used Static Query

My code is like that:

import React from "react";
import { useStaticQuery, graphql} from "gatsby";


export default function MenuMD () {
    const { data } = useStaticQuery(
    graphql`
      query {
                allFile(filter: {sourceInstanceName: {eq: "markdown"}}) {
                    edges {
                        node {
                            childrenMarkdownRemark {
                                frontmatter {
                                    slug
                                    title
                                }
                            }
                        }
                    }
                }
      }
    `
    )
    console.log('static data', data);

    return<>Menu from MarkDown</>
}

the expected result from http://localhost:8000/___graphql is something like that:

{
  "data": {
    "allFile": {
      "edges": [
        {
          "node": {
            "childMarkdownRemark": {
              "frontmatter": {
                "slug": "/projet_m",
                "title": "Projet M"
              }
            }
          }
        },
        {
          "node": {
            "childMarkdownRemark": {
              "frontmatter": {
                "slug": "/projet_n",
                "title": "Projet N"
              }
            }
          }
        }
      ]
    }
  },
  "extensions": {}
}

May be there is a reason for this undefined return?

CodePudding user response:

Assuming that the query is working in the GraphiQL environment and there's a "markdown" sourceInstanceName in your data structure, try it like this:

export default function MenuMD() {
  const data = useStaticQuery(
    graphql`
      query {
        allFile(filter: { sourceInstanceName: { eq: "markdown" } }) {
          edges {
            node {
              childrenMarkdownRemark {
                frontmatter {
                  slug
                  title
                }
              }
            }
          }
        }
      }
    `
  );
  console.log("static data", data);

  return <>Menu from MarkDown</>;
}

There's nothing wrong using a static query in a component rather than a page, the result must be exactly the same (in terms of output).

Your data should be inside data.allFile.edges, not directly destructuring the result of the static query as data. That's why data was undefined in your case.

  • Related