微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Apollo Client:更新缓存时的 writeFragment 或 readFragment?

如何解决Apollo Client:更新缓存时的 writeFragment 或 readFragment?

在 useMutation 的 update 钩子中,Apollo 的文档建议使用 writeFragment获取对新添加对象的内部引用。我觉得这很奇怪,因为该对象已存在于缓存中。所以我用 readFragment 对其进行了测试,果然,它运行良好。在这个用例中,是否更喜欢使用 writeFragment 而不是 readFragment

示例 1:

https://www.apollographql.com/docs/react/data/mutations/#making-all-other-cache-updates

const [addTodo] = useMutation(ADD_Todo,{
    update(cache,{ data: { addTodo } }) {
      cache.modify({
        fields: {
          todos(existingTodos = []) {
            const newTodoRef = cache.writeFragment({
              data: addTodo,fragment: gql`
                fragment NewTodo on Todo {
                  id
                  type
                }
              `
            });
            return [...existingTodos,newTodoRef];
          }
        }
      });

摘自该页面

在 cache.writeFragment 的帮助下,我们得到了一个内部引用 添加的待办事项,然后将该引用存储在 ROOT_QUERY.todos 中 数组。

示例 2:

https://www.apollographql.com/docs/react/caching/cache-interaction/#example-updating-the-cache-after-a-mutation

const [addComment] = useMutation(ADD_COMMENT,{
  update(cache,{ data: { addComment } }) {
    cache.modify({
      fields: {
        comments(existingCommentRefs = [],{ readField }) {
          const newCommentRef = cache.writeFragment({
            data: addComment,fragment: gql`
              fragment NewComment on Comment {
                id
                text
              }
            `
          });
          return [...existingCommentRefs,newCommentRef];
        }
      }
    });
  }
});

摘自该页面

注释已被 useMutation 添加到缓存中。 因此,cache.writeFragment 返回对现有的引用 对象。

我也在 Apollo Client 的讨论区 (https://github.com/apollographql/apollo-client/discussions/7515) 上发布了这个问题,但那里没有得到回复

解决方法

此处解释了在从缓存中获取项目时使用 writeFragment 而不是 readFragment 的好处(摘自 https://www.apollographql.com/docs/react/caching/cache-interaction/#example-updating-the-cache-after-a-mutation):

如果您使用缓存能够识别的 options.data 对象调用 writeFragment,根据其 __typename 和主键字段,您可以避免将 options.id 传递给 writeFragment。

无论您是明确提供 options.id 还是让 writeFragment 使用 options.data 计算出来,writeFragment 都会返回对标识对象的引用。

这种行为使得 writeFragment 成为获取缓存中现有对象的 Reference 的好工具,可以派上用场 为 useMutation 编写更新函数时

这是违反直觉的,因为名称 writeFragment 暗示它用于写入缓存而不是从中读取,但它似乎是推荐的最佳做法。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。