在 apollo-client 中从客户端缓存中删除项目的正确方法

Cro*_*roc 6 typescript reactjs graphql react-apollo apollo-client

我在我的 React(Typescript) 应用程序中使用带有 Apollo-Client 的 GraphQL 和内存缓存。缓存在添加的新项目上更新,它可以正常工作且没有错误。

当删除项目时,从 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) },
        });
      }
    },
  });
Run Code Online (Sandbox Code Playgroud)

该功能有效,前端使用缓存中的正确项目更新,但是控制台中显示以下错误:


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
Run Code Online (Sandbox Code Playgroud)

有没有更好的方法来更新缓存,这样就不会收到这个错误?

Jos*_*Cho 7

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

第一个是在调用之前清除缓存中的内容cache.writeQuery

  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,
  });
Run Code Online (Sandbox Code Playgroud)

简而言之,这会刷新您的缓存,以便您的新数据将成为新的事实来源。不用担心丢失旧数据。

apollo-client v3 的替代建议在同一线程中进一步发布:

cache.modify({
  fields: {
    notifications(list, { readField }) {
      return list.filter((n) => readField('id', n) !==id)
    },
  },
})
Run Code Online (Sandbox Code Playgroud)

这种方式删除了很多样板文件,因此您不需要使用readQueryevictwriteQuery。问题是,如果你运行 Typescript,你会遇到一些实现问题。在幕后,使用的格式是InMemoryCacheformat 而不是通常的 GraphQL 数据。您将看到Reference未推断的对象、类型以及其他奇怪的东西。


Mor*_*osh 6

我也面临完全相同的警告,不幸的是,除了这里建议的解决方案之外,没有提出解决方案: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;
            },
          },
        },
      },
    }
  }),
});
Run Code Online (Sandbox Code Playgroud)

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

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

我想知道,如果有更好的解决方案