Cat Boxer
Cat Boxer

Reputation: 47

Gatsby source plugin only showing last item in array in GraphQL

When I console log after I run build 6 objects show up in my drinks array. They also show up when I run develop. But when I query graphQL only the last object in my array is available. I am new to gatsby and graphQL so included image just in case my query was off. Code is from my gatsby-node.js file:

exports.sourceNodes = async (
    { actions, createContentDigest, createNodeId,}
  ) => {
  const NODE_TYPE = "CocktailRecipes";
    try{ 
    const response = await fetch(`https://www.thecocktaildb.com/api/json/v1/1/search.php?s=vodka`)
    const data = await response.json();
    const {drinks} = data;
    console.log(drinks)
    drinks.forEach((drink) => {
      actions.createNode({
        ...drink,
        id: createNodeId(`${NODE_TYPE }-${drink.id}`),
        parent:null,
        children:[],
        internal:{
          type:NODE_TYPE,
          content:JSON.stringify(drink),
          contentDigest: createContentDigest(drink)
        }
      })
    })
    }
    catch(error){ 
      console.log("ERROR")
      console.log(error)
    }
  }

only one object showing in graphQL

If anyone could help it would be very much appreciated as I've been banging my head on a wall for awhile now. I've done a gatsby clean. I've tried map instead of forEach

Upvotes: 1

Views: 328

Answers (1)

Ferran Buireu
Ferran Buireu

Reputation: 29335

I've faced exactly the same issue as you a few months ago and, in my case was that I needed to set a valid internal id for each element to allow GraphQL to create a proper schema for each node if not, the id is overridden in each element and it only takes the last one.

In your case, it seems that some field is wrong, making the following expression invalid:

    id: createNodeId(`${NODE_TYPE }-${drink.id}`),

Try debugging more what's receiving and changing it to some hardcoded value. Something like:

    id: drink.id,

Keep in mind that, if the ids are different for each node, you don't need to use createNodeId API for debugging purposes (but it's recommended).

Upvotes: 1

Related Questions