简体   繁体   中英

Deleting Record from List, Apollo GraphQL Optimistic UI Mutation

I'm looking for a way to have an optimistic Ui delete an Item from a list.

The query for the list is:

myQuery{
 Foo:{
  Bar:{
    id
 }
}

delete mutation:

mutation deleteBar(input: barInput!){
 deleteBarItem: (responds Boolean for success)
}

How do I structure the optimisticResponse?

deleteBarItem({
 variables:{
  barInput:{
   id: idToBeDeleted
  }
 },
optimisticResponse:{
  ?????
},
update: (cache, { data}) => { ...manipulate the list in cache}
})

Thanks to xadm for providing an example in the comments to reference

deleteBarItem({
 variables:{
  barInput:{
   id: idToBeDeleted
  }
 },
optimisticResponse:{
  deleteBarItem: true,
  foo:{
   id: idToBeDeleted,
   __typename: "Bar"
  }
},
update: (cache, { data}) => { ...manipulate the list in cache}
})

A couple key notes.

Cache: Uses __typename and id to reference objects. Using the optimistic ui to "delete" and Item you need to set the cache with an object that has no other information associated with it.

update: This function is run twice. Once with the optimistic results and then again when the mutation comes back. With my example of the mutation returning a boolean I added a filter to the list based on that boolean to remove deleted item from the list or leave it intact.

Here's a Medium article with one example for how to use OptimisticResponse for deleting an item from a list.

It'd be helpful to see your schema, but here's a working example from a toy to-do app I built with OptimisticResponse working for deleting items from the list:

optimisticResponse: {
  __typename: "Mutation",
  deleteResolution: {
    __typename: "Resolution",
    _id
  }
}

You can verify your OptimisticResponse is working by setting your Network speed to Slow 3G in the dev console and ensuring that the item still gets removed immediately.

Side note - you can use filter in the update function instead of a boolean to cleanly create a new array with the item removed. Here's how I do this in the to-do app linked above, where _id is the id of the item to be removed that gets passed in as a prop to the DeleteResolution component:

resolutions = resolutions.filter(
  resolution => resolution._id !== _id
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM