Home > Net >  GatsbyJS GraphQL - Error when query with "edges", Could anybody please explain this quer
GatsbyJS GraphQL - Error when query with "edges", Could anybody please explain this quer

Time:09-16

I've got an error when I query using "useStaticQuery" in "GatsbyJS" as the following code:

const data = useStaticQuery(graphql`
  query ExperienceQuery {
    allExperienceJson {
      edges {
        node {
            src
            desc
          }
        }
      }
    }
  `);

enter image description here

but when I remove "edges", it works properly.

const Experience = () => {
  const data = useStaticQuery(graphql`
  query ExperienceQuery {
    allExperienceJson {
      nodes {
          src
          desc
        }
      }
    }
  `);

Could anybody please explain this query error?

CodePudding user response:

Could anybody please explain this query error?

edges and node(s) are both children of the main GraphQL node. Assuming you're using gatsby-transformer-json to source your allExperience from a JSON, according to the docs it should create both nodes (edges and node).

However, depending on your Gatsby version (since it's an official plugin) it may be creating nodes node directly, which in fact it's the same as doing edges.nodes (in terms that node(s) always holds the array of data). If your Gatsby version is creating a structure of allExperienceJson.nodes and you are trying to get allExperienceJson.edges.node your code will break.

In your case, if the second approach works, I would leave it as is. However, double-check the query in the GraphiQL playground (localhost:8000/___graphql) because you may be facing some rehydration issues. You should always use the query that you tested in the GraphiQL environment.

For example: if the first query works in the GraphiQL playground, but the code fails, you are facing a rehydration issue, which means that at the time you are trying to get allExperience it's not filled hence the .slice fails. If that's the case, add a safeguard (check if the data is different from null before the slice) or use the nullish coalescent operator (?):

const allExperience = data.allExperienceJson?.edges?.node ?? []

In that way are bypassing a potential null data fetch at a glance (avoiding the code to break) because of the [] assignation and when the query is rehydrated allExperience should contain the correct data.

If the second query is the one that works in the GraphiQL playground, forget what I said and go through using it.

  • Related