javascript - 如何在 Apollo 中使用乐观的 UI 处理删除突变?

标签 javascript vue.js graphql apollo vue-apollo

https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-mutation-options-optimisticResponse

有大量文档和教程展示了涉及添加内容的突变 updateoptimisticResponse 属性的使用,但我没有看到任何涉及删除的内容。

我不确定代码应该是什么样子。对于 create 突变,您希望通过 update 将新项目添加到 Apollo 缓存,并使用 optimisticResponse 将临时副本添加到 UI。但是对于删除,“显示”删除没有意义,因为它缺少数据。

这是我在 Vue 组件的一个方法中得到的,部分正确:

async handleDelete(trackId: number) {
  const result = await this.$apollo.mutate({
    mutation: require('@/graphql/delete-tracks.gql'),
    variables: {
      ids: [trackId],
    },
    update: store => {
      const data: { getTracks: TrackList } | null = store.readQuery({
        query: getTracksQuery,
        variables: this.queryVars,
      });

      if (data && data.getTracks) {
        data.getTracks.data = data.getTracks.data.filter(
          (track: Track) => track.id !== trackId
        );
        --data.getTracks.total;
      }

      store.writeQuery({
        query: getTracksQuery,
        variables: this.queryVars,
        data,
      });
    },
    optimisticResponse: {},
  });

  console.log('result:', result);
},

我发现我基本上需要从 Apollo 缓存中删除已删除的项目,这部分似乎工作得很好。虽然视觉移除不会立即发生,因为没有 optimisticResponse。这是我完全不知道如何着手写作的部分。

最佳答案

明白了,比我想象的简单多了。我只是不太明白 optimisticResponse 如何与 update 一起发挥作用。

optimisticResponse: {
  __typename: 'Mutation',
  deleteTracks: [trackId],
},

因此 update 方法将从 optimisticResponse 获取此结果并从缓存中删除该轨道 ID。 update 将第二次调用 GraphQL 服务器响应,并且 Apollo 缓存将被协调。

关于javascript - 如何在 Apollo 中使用乐观的 UI 处理删除突变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54819678/

相关文章:

javascript - CSS HTML - DIV高度填充剩余空间

javascript - 我如何使用 $location.state()

vue.js - 带有 No-SSR 的 Vue2-Leaflet 导致 Window is not Defined 错误

javascript - Express.js + lint 报错

javascript - 在 GraphQL 中从 API 转换数据的最佳方法是什么

reactjs - 使用 @graphql-codegen/cli 获取 graphql 查询中的子类型

javascript - 在 React Native 中使用 React-navigation 时,无法获取 Relay 中的数据

javascript - 当我更改 http.jsonp() URL 时,JSON 数据未显示

javascript - 隐私浏览模式(隐身)下的 Web 存储(sessionStorage 和 localStorage)

javascript - 有没有办法在这个 v-for 中正确使用索引而不出现错误