从Apollo客户端中的客户端缓存中删除项目的正确方法

时间:2020-07-30 05:36:35

标签: reactjs typescript graphql react-apollo apollo-client

我在带有内存缓存的React(Typescript)应用程序中将GraphQL与Apollo-Client一起使用。缓存会根据要添加的新项目进行更新,这可以正常工作而不会出错。

当删除项目时,从GraphQL Apollo-Server后端返回一个字符串,指出成功的删除操作,该操作将启动要调用的更新函数,该函数读取缓存,然后通过过滤出该项目的ID对其进行修改。这是使用Apollo-Client的突变挂钩执行的。

const [deleteBook] = useMutation<{ deleteBook: string }, DeleteBookProps>(DELETE_BOOK_MUTATION, {
    variables: { id },
    onError(error) {
      console.log(error);
    },
    update(proxy) {
      const bookCache = proxy.readQuery<{ getBooks: IBook[] }>({ query: GET_BOOKS_QUERY });
      if (bookCache) {
        proxy.writeQuery<IGetBooks>({
          query: GET_BOOKS_QUERY,
          data: { getBooks: bookCache.getBooks.filter((b) => b._id !== id) },
        });
      }
    },
  });

该功能正常运行,并且前端使用缓存中的正确项目更新了前端,但是控制台中显示以下错误:


Cache data may be lost when replacing the getBooks field of a Query object.

To address this problem (which is not a bug in Apollo Client), define a custom merge function for the Query.getBooks field, so InMemoryCache can safely merge these objects:

  existing: [{"__ref":"Book:5f21280332de1d304485ae80"},{"__ref":"Book:5f212a1332de1d304485ae81"},{"__ref":"Book:5f212a6732de1d304485ae82"},{"__ref":"Book:5f212a9232de1d304485ae83"},{"__ref":"Book:5f21364832de1d304485ae84"},{"__ref":"Book:5f214e1932de1d304485ae85"},{"__ref":"Book:5f21595a32de1d304485ae88"},{"__ref":"Book:5f2166601f6a633ae482bae4"}]
  incoming: [{"__ref":"Book:5f212a1332de1d304485ae81"},{"__ref":"Book:5f212a6732de1d304485ae82"},{"__ref":"Book:5f212a9232de1d304485ae83"},{"__ref":"Book:5f21364832de1d304485ae84"},{"__ref":"Book:5f214e1932de1d304485ae85"},{"__ref":"Book:5f21595a32de1d304485ae88"},{"__ref":"Book:5f2166601f6a633ae482bae4"}]

For more information about these options, please refer to the documentation:

  * Ensuring entity objects have IDs: https://go.apollo.dev/c/generating-unique-identifiers
  * Defining custom merge functions: https://go.apollo.dev/c/merging-non-normalized-objects

是否有更好的方法来更新缓存,从而不会收到此错误?

2 个答案:

答案 0 :(得分:4)

我也面临完全相同的警告,不幸的是,除了这里建议的解决方案外,没有提出其他解决方案:https://go.apollo.dev/c/merging-non-normalized-objects

const client = new ApolloClient({
  ....
  cache: new InMemoryCache({
    typePolicies: {
      Query: {
        fields: {
          getBooks: {
            merge(existing, incoming) {
              return incoming;
            },
          },
        },
      },
    }
  }),
});

(我不确定我是否正确地编写了您的字段和类型,所以您可能会稍微更改此代码)

基本上,以上代码使apollo客户端如何处理可合并的数据。在这种情况下,我只需用新数据替换旧数据。

我想知道是否有更好的解决方案

答案 1 :(得分:2)

我也遇到了同样的问题。我遇到了一个 GitHub 线程,它提供了两种替代解决方案 here

首先是在调用 plane0.worldTransform.rotation = planeTracker.worldTransform.lookAt(camera.worldTransform.position).rotation; 之前清除缓存中的内容:

cache.writeQuery

简而言之,这会刷新您的缓存,因此您的新数据将成为新的事实来源。无需担心丢失旧数据。

在下面的 same thread 中进一步发布了对 apollo-client v3 的替代建议:

  cache.evict({
    // Often cache.evict will take an options.id property, but that's not necessary
    // when evicting from the ROOT_QUERY object, as we're doing here.
    fieldName: "notifications",
    // No need to trigger a broadcast here, since writeQuery will take care of that.
    broadcast: false,
  });

这种方式删除了很多样板文件,因此您不需要使用 cache.modify({ fields: { notifications(list, { readField }) { return list.filter((n) => readField('id', n) !==id) }, }, }) readQueryevict。问题是,如果您正在运行 Typescript,您会遇到一些实现问题。在幕后使用的格式是 writeQuery 格式,而不是通常的 GraphQL 数据。您会看到 InMemoryCache 对象、无法推断的类型以及其他奇怪的东西。