[英]How to handle delete mutations with optimistic UI in Apollo?
https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-mutation-options-optimisticResponse https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-mutation-options-optimisticResponse
There's plenty of documentation and tutorials showing use of the mutation update
and optimisticResponse
properties involving adding things, but I haven't seen any involving deletions. 有大量的文档和教程显示了使用变异update
和optimisticResponse
属性涉及添加事物的用法,但是我还没有看到涉及缺失的任何信息。
I'm not exactly sure how that code should look. 我不确定该代码的外观。 With a create mutation, you want to add the new item to the Apollo cache via update
and add a temporary copy to the UI using optimisticResponse
. 对于create突变,您想通过update
将新项目添加到Apollo缓存中,并使用optimisticResponse
将临时副本添加到UI中。 But with a deletion, it doesn't make sense to "show" the deletion since it's the absence of data. 但是对于删除,“显示”删除是没有意义的,因为它没有数据。
This is what I've got in a method in my Vue component, which is partly correct: 这是我在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);
},
I figured out that I basically need to remove the deleted item from the Apollo cache, and that part seems to work great. 我发现我基本上需要从Apollo缓存中删除已删除的项目,并且该部分似乎工作得很好。 Though the visual removal doesn't happen immediately, since there's no optimisticResponse
. 尽管不会立即发生视觉移除,但因为没有optimisticResponse
。 That's the part I have absolutely no idea how to go about writing. 那是我绝对不知道如何写作的部分。
Got it, it was much simpler than I thought. 知道了,它比我想的要简单得多。 I just didn't quite understand how optimisticResponse
came into play with update
. 我只是不太了解optimisticResponse
如何与update
发挥作用。
optimisticResponse: {
__typename: 'Mutation',
deleteTracks: [trackId],
},
So the update
method will take this result from optimisticResponse
and remove that track ID from the cache. 因此, update
方法将从optimisticResponse
获取此结果,并从缓存中删除该轨道ID。 update
will be called a second time with the GraphQL server response, and the Apollo cache will be reconciled. GraphQL服务器响应将再次调用update
,并且将协调Apollo缓存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.