2
votes

I try to update Apollo cache after running Mutation. For this, i use mutate method :

client.mutate({
  mutation: CREATE_PLAYLIST,
  variables: { ...playlistUpdated, users: [1] },
  update: cache => {
    const { playlists } = cache.readQuery({ query: GET_USER_PLAYIST });

    cache.writeQuery({
      query: GET_USER_PLAYIST,
      data: { playlists: playlists.concat(playlistUpdated) }
    });
  }
});

But on writeQuery function, i've this error : TypeError: TypeError: undefined is not an object (evaluating 'data.playlists'). I'm not really understand why i've this error because data.playlists exist on GET_USER_PLAYIST query response :/

const GET_USER_PLAYIST = gql`
  {
    playlists(where: { users: { id: 1 } }) {
      name
      id
    }
  }
`;

Anyone can help me ?

Thank you community !

1
Looks like a typo. When calling writeQuery, you're constructing an object with a playlist property, but it should be playlists based on your query.Daniel Rearden
Hi ! Mmm yes, i think it's wrong c/p, but same results with playlists :(s-leg3ndz

1 Answers

1
votes

The query you are caching has the variables:

where: { users: { id: 1 } }

So the in memory cache saves the query with these query variables. If you want to read / write the query you would also need to add the correct variables in

cache.readQuery({ query: GET_USER_PLAYIST });

cache.writeQuery({ ... });

Take a look at the second example in the docu

In youre case it should be something like:

const { playlists } = client.readQuery({
  query: GET_USER_PLAYIST,
  variables: {
    where: { users: { id: 1 }} // maybe the variables need to be passed in when updating the cache
  },
});

cache.writeQuery({
  query: GET_USER_PLAYIST,
  data: {
    playlists: playlists.concat(playlistUpdated)
  },
  variables: {
    where: { users: { id: 1 }}
  }
});