突变后更新Apollo缓存

时间:2019-07-17 14:53:48

标签: reactjs apollo react-apollo

我尝试在运行Mutation后更新Apollo缓存。为此,我使用mutate方法:

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) }
    });
  }
});

但是在writeQuery函数上,我遇到了这个错误:TypeError: TypeError: undefined is not an object (evaluating 'data.playlists')。我不太明白为什么会出现此错误,因为{。{1}}查询响应中存在data.playlists:/

GET_USER_PLAYIST

有人可以帮助我吗?

谢谢社区!

1 个答案:

答案 0 :(得分:0)

您要缓存的查询具有变量:

where: { users: { id: 1 } }

因此内存缓存将查询与这些查询变量一起保存。如果您想读/写查询,还需要在

中添加正确的变量。

cache.readQuery({ query: GET_USER_PLAYIST });

cache.writeQuery({ ... });

看看docu

中的第二个示例

在您的情况下,它应该类似于:

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 }}
  }
});