ffxsam
ffxsam

Reputation: 27743

How to handle delete mutations with optimistic UI in Apollo?

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.

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. 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:

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. Though the visual removal doesn't happen immediately, since there's no optimisticResponse. That's the part I have absolutely no idea how to go about writing.

Upvotes: 4

Views: 2042

Answers (1)

ffxsam
ffxsam

Reputation: 27743

Got it, it was much simpler than I thought. I just didn't quite understand how optimisticResponse came into play with 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 will be called a second time with the GraphQL server response, and the Apollo cache will be reconciled.

Upvotes: 2

Related Questions