【问题标题】:Gatsby source plugin only showing last item in array in GraphQLGatsby 源插件仅显示 GraphQL 中数组中的最后一项
【发布时间】:2021-03-25 06:26:12
【问题描述】:

当我运行 build 6 后控制台日志显示在我的饮料数组中。当我运行开发时,它们也会出现。但是当我查询 graphQL 时,只有数组中的最后一个对象可用。我是 gatsby 和 graphQL 的新手,所以包含图片以防我的查询关闭。 代码来自我的 gatsby-node.js 文件:

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

如果有人能提供帮助,我将不胜感激,因为我已经把头撞在墙上一段时间了。我已经完成了 gatsby clean。我试过 map 而不是 forEach

【问题讨论】:

    标签: javascript node.js graphql gatsby gatsby-plugin


    【解决方案1】:

    几个月前我遇到了和你完全相同的问题,在我的情况下,我需要为每个元素设置一个有效的内部 id 以允许 GraphQL 为每个节点创建适当的架构(如果不是) ,id 在每个元素中都会被覆盖,并且只取最后一个。

    在您的情况下,似乎某些字段是错误的,使以下表达式无效:

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

    尝试更多地调试正在接收的内容并将其更改为某个硬编码值。比如:

        id: drink.id,
    

    请记住,如果每个节点的 ids 不同,则您无需使用 createNodeId API 进行调试(但建议这样做)。

    【讨论】:

    • 谢谢!这正是问题所在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-06
    • 2021-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多