【问题标题】:Apollo Client: cache.modify does not work?Apollo 客户端:cache.modify 不起作用?
【发布时间】:2020-10-12 01:44:51
【问题描述】:

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

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

const writeInitialData = () => {
    cache.writeQuery({
        query: gql`
            query {
                test
            }
        `,
        data: {
            test: {
                __typename: 'test',
                id: 'id1',
                string: 'initial string',
            }
        },
    });
};

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

updateTest: (_, __, { cache }) => {
    cache.modify({
      id: cache.identify({
        __typename: 'test',
        id: 'id1',
      }),
      fields: {
        string: 'changed string',
      },
    });
}

但是,缓存中的值并没有改变,而且如果我 console.log() 得到 cache.modify 的返回值,它给了我false,表示缓存没有更新。

【问题讨论】:

    标签: apollo react-apollo apollo-client


    【解决方案1】:

    在 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 的列表。

    【讨论】:

      【解决方案2】:

      您应该使用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,
      })

      【讨论】:

        猜你喜欢
        • 2018-02-22
        • 2019-01-08
        • 1970-01-01
        • 2021-07-05
        • 2019-01-12
        • 2020-09-16
        • 2021-08-31
        • 2020-09-17
        • 2019-07-25
        相关资源
        最近更新 更多