【问题标题】:ApolloClient: Delete item from cache across all queries?ApolloClient:跨所有查询从缓存中删除项目?
【发布时间】:2020-10-20 12:30:39
【问题描述】:

当涉及到 ApolloClient 缓存时,我熟悉执行更新和插入的各种方法,但这个问题是关于删除的。

假设用户选择删除“id”为 123 的“note”项。我希望在缓存中完全删除“note:123”。有没有办法做到这一点?

例如,在进行更新的情况下,我经常使用writeFragment 来更新特定的注释,这符合我的预期,在所有查询中更新该注释。但是,我注意到明显缺少 deleteFragment 方法。我错过了什么吗?

【问题讨论】:

  • 你只是想删除缓存查询中id为123的项还是删除缓存中的所有数据?
  • 我只想删除那个项目。即用户删除了注释,因此该注释不应再出现在任何查询中。

标签: apollo apollo-client


【解决方案1】:

看起来 ApolloClient v3 允许您为此使用 evict()。据我所知,这是删除项目的唯一方法,而无需知道它出现在其下的每个查询和变量组合。

【讨论】:

    【解决方案2】:

    您可以通过update 选项在突变后更新您的缓存。试试这个:

    const DELETE_ITEM = gql`
      DeleteItem($id: ID!) {
        deleteItem(id: $id) {
          ...
        }
      }
    `
    
    const LIST_ITEMS = gql`
      ListItem($query: ListItemInput!) {
        listItem(query: $query) {
          items {
            id
          }
        }
      }
    `
    
    const [deleteItem] = useMutation(DELETE_ITEM, {
      update: (cache, { deleteItem }) => {
        const { listItem } = cache.readQuery(LIST_ITEMS, {
          variables: {
            query: {...}
          }
        })
        const index = listItem.items.findIndex(
          item => item.id === deleteMessage.id
        )
        if (index > -1) {
          listItem.items.splice(index, 1)
          cache.writeQuery({
            query: LIST_ITEMS,
            {
              variables: {
                query: {...}
              }
            },
            data: {
              listItem,
            },
          })
        }
      }
    })

    【讨论】:

    • 这只会更新单个查询的缓存。但单个项目可能存在于任意数量的查询中。
    猜你喜欢
    • 1970-01-01
    • 2023-01-09
    • 1970-01-01
    • 2010-10-16
    • 2019-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多