Apollo Client: cache.modify does not work?

Viewed 5947

I can't seem to get my cache to update after a mutation, although I passed the typename and id to reference the object to modify. What am I doing wrong? I reproduced a simple example here.

I first initialized my cache with the data -

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

I then executed the mutation on my client.

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

however, the value in the cache did not change, and furthermore if I console.log() the returned value of cache.modify, it gives me false, implying that there is no update to the cache.

2 Answers

in Apollo client v3, you can use new method as [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. authorization is a modifier function.
  2. readField is a utility function.
  3. _id is an own identifier in the cache.
  4. existingAuth is the list of __refs.

You should use mutation to update the cache. Try this:

...
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,
})

Related