【问题标题】:How to get and set a ref for a newly cached related object in Apollo client InMemoryCache?如何在 Apollo 客户端 InMemoryCache 中获取和设置新缓存的相关对象的引用?
【发布时间】:2021-01-15 13:16:31
【问题描述】:

我有一组类似的相关项目:

book {
  id
  ...
  related_entity {
    id
    ...
  }
}

其中 apollo 缓存为两个单独的缓存对象,其中 book 上的 related_entity 字段是对 EntityNode 对象的引用。这很好,相关实体数据也在book 的上下文之外的其他地方使用,因此将其分开工作,一切看起来都很好,并且按预期更新......除非相关实体没有存在于初始提取(因此book 对象上的引用为空),我稍后创建一个。

我尝试将update 函数添加到useMutation 钩子,根据他们的文档创建上述related_entityhttps://www.apollographql.com/docs/react/caching/cache-interaction/#example-adding-an-item-to-a-list,如下所示:

const [mutateEntity, _i] = useMutation(CREATE_OR_UPDATE_ENTITY,{
    update(cache, {data}) {
        cache.modify({
          id: `BookNode:${bookId}`,
          fields: {
            relatedEntity(_i) {
              const newEntityRef = cache.writeFragment({
                fragment: gql`
                  fragment NewEntity on EntityNode {
                    id
                    ...someOtherAttr
                  }`,
                data: data.entityData
              });
              return newEntityRef;
            }
          }
        })
    }
  });

但无论我尝试什么,newEntityRef 始终未定义,即使新的 EntityNode 肯定在缓存中并且可以使用完全相同的片段很好地读取。我可以放弃并强制重新获取 Book 对象,但数据已经就在那里

我做错了什么/有更好的方法吗? 除非你有它的标识符,否则是否有另一种方法来获取缓存对象的引用?

【问题讨论】:

标签: javascript graphql react-apollo apollo-client apollo-cache-inmemory


【解决方案1】:

看起来这实际上是apollo-cache-persist 的问题 - 我删除了它,上面的代码按照文档的预期运行。看起来我也可以使用不同的包名称 apollo3-cache-persist 更新到新版本,但我最终还是不需要缓存持久性。

【讨论】:

    猜你喜欢
    • 2019-09-27
    • 2021-02-05
    • 1970-01-01
    • 2021-04-21
    • 2019-04-02
    • 2017-03-18
    • 2021-03-11
    • 2021-02-01
    • 2021-06-05
    相关资源
    最近更新 更多