ApolloClient:从所有查询的缓存中删除项目?

时间:2020-06-30 08:37:57

标签: apollo apollo-client

对于ApolloClient缓存,我熟悉执行更新和插入的各种方法,但是这个问题与删除有关。

比方说,用户选择删除“ id”为123的“ note”项目。我希望在缓存中完全删除“ note:123”。有办法吗?

例如,在进行更新的情况下,我经常使用writeFragment更新特定的注释,而这正是我期望的,可以在所有查询中更新该注释。但是,我注意到明显缺乏deleteFragment方法。我想念什么吗?

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可以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,
        },
      })
    }
  }
})