Apollo客户端:cache.modify不起作用?

时间:2020-06-22 08:29:44

标签: apollo react-apollo apollo-client

尽管我传递了类型名和ID来引用要修改的对象,但在突变后我似乎无法更新其缓存。我究竟做错了什么? 我在这里转载了一个简单的例子。

我首先用数据初始化了缓存-

marcha

然后我在客户上执行了突变。

   dhRegistro              | marcha
   ----------------------------------
   2020-06-15 12:28:17.043  | 1
   2020-06-15 12:43:46.803  | 1
-> 2020-06-15 12:44:20.143  | 0
   2020-06-15 14:01:22.893  | 0
   2020-06-15 14:01:22.920  | 0
   2020-06-15 14:01:23.030  | 0
   2020-06-15 14:02:55.937  | 0
   2020-06-15 14:04:05.693  | 1
-> 2020-06-15 14:23:19.817  | 0
   2020-06-15 14:57:02.027  | 1
-> 2020-06-15 15:13:02.143  | 0
   2020-06-15 15:20:08.200  | 1
-> 2020-06-15 15:39:22.333  | 0
   2020-06-15 15:50:36.430  | 1
-> 2020-06-15 16:06:35.557  | 0
   2020-06-15 16:08:18.527  | 1
-> 2020-06-15 16:27:32.687  | 0
   2020-06-15 16:36:21.763  | 1
   2020-06-15 16:51:46.587  | 1
-> 2020-06-15 17:11:12.000  | 0
   2020-06-15 17:20:01.007  | 1
   2020-06-15 17:35:27.313  | 1

但是,缓存中的值没有更改,此外,如果我用console.log()返回cache.modify的值,它会给我const writeInitialData = () => { cache.writeQuery({ query: gql` query { test } `, data: { test: { __typename: 'test', id: 'id1', string: 'initial string', } }, }); }; ,这意味着缓存没有更新。

3 个答案:

答案 0 :(得分:0)

我建议您使用apollo useMutation挂钩和更新方法。只需访问它能产生奇迹的阿波罗官方网站即可。

答案 1 :(得分:0)

您应使用mutation更新缓存。试试这个:

...
const resolvers = {
  Mutation: {
    updateTest: (_, args , { cache }) => {
      const { test } = cache.readQuery({
                query: gql`
                query {
                    test
                }
            `,
            })
      cache.writeData({
          data: {
            test: {...test, args.string}
          },
      })
  }
}

...
const client = new ApolloClient({
  cache,
  link,
  resolvers,
})

答案 2 :(得分:0)

在 Apollo 客户端 v3 中,您可以使用新方法 [cache.modify][1]

 update: (cache, { data }) => {
        // Update cache with modify method
        cache.modify({
          fields: {
            authorization(existingAuth = [], { readField }) {
              return existingAuth.filter(
                (rule) =>
                  readField('id', rule) !== data.id,
              );
            },
          },
        });
      },
  1. 授权是一个修饰函数。
  2. readField 是一个实用函数。
  3. _id 是缓存中自己的标识符。
  4. existingAuth 是 __refs 的列表。