简体   繁体   English

从列表中删除记录,Apollo GraphQL乐观UI突变

[英]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. 我正在寻找一种使Ui乐观地从列表中删除项目的方法。

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? 如何构造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 感谢xadm在注释中提供示例以供参考

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. 缓存:使用__typename和id引用对象。 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. 使用乐观的ui来“删除”和Item,您需要使用一个没有任何其他信息与其关联的对象来设置缓存。

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. 这是一篇中型文章 ,其中包含一个示例,说明如何使用OptimisticResponse从列表中删除项目。

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构建的玩具待办事项应用程序中的一个有效示例,用于从列表中删除项目:

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. 您可以通过在开发者控制台中将“网络速度”设置为“慢速3G”并确保仍立即删除该项目来验证OptimisticResponse是否正常工作。

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: 这是我在上面链接的待办事项应用程序中执行的操作,其中_id是要作为道具传递给DeleteResolution组件的要删除项目的ID:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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