【问题标题】:Update Apollo cache after Mutation变异后更新 Apollo 缓存
【发布时间】:2019-11-26 11:00:12
【问题描述】:

我尝试在运行 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')。我不太明白为什么会出现此错误,因为GET_USER_PLAYIST 查询响应中存在 data.playlists :/

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

谁能帮帮我?

感谢社区!

【问题讨论】:

  • 看起来像是错字。调用writeQuery 时,您正在构造一个具有playlist 属性的对象,但根据您的查询,它应该是playlists
  • 嗨!嗯,是的,我认为这是错误的 c/p,但与 playlists 的结果相同 :(

标签: reactjs apollo react-apollo


【解决方案1】:

您正在缓存的查询具有变量:

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

【讨论】:

    猜你喜欢
    • 2020-05-09
    • 2022-11-11
    • 2020-02-03
    • 2021-03-24
    • 2020-05-11
    • 2020-02-12
    • 2021-10-06
    • 2020-02-28
    • 2021-01-13
    相关资源
    最近更新 更多