如何在 ApolloClient v3 中删除单个缓存

时间:2021-01-20 10:20:16

标签: reactjs apollo apollo-client

我已经使用了 24 小时,但似乎没有任何效果..... 正确。我看过的文档:

  1. How to invalidate cached data in Apollo and handle updating paginated queries
  2. Not sure what this does

我有一个搜索栏,可以查询我的 GraphQL (GQ) 服务器。单击时,下拉列表会显示最近的搜索。当它打开时,GQ 被获取。为了简单起见,我将只关注概念:

  1. 当我删除最近的搜索时,匹配的缓存搜索查询也应该被删除。删除了什么?数据库中的相关缓存和数据。
// RecentSearches component

import { GetRecentSearches, DeleteRecentSearchDetails, QuerySearches } from '../somewhere';

// Mutation function
const [deleteRecentSearch] = useMutation(DeleteRecentSearchDetails);

// Query
const { loading, data, refetch, networkStatus } = useQuery(GetRecentSearches, {
  notifyOnNetworkStatusChange: true
});

这是我遇到问题的地方。单击 deleteRecentSeach 后,我应该能够删除最近搜索的缓存查询。如果我不这样做,重新输入相同的查询将不会获取,因为缓存已经在浏览器中,所以我必须先删除它。

deleteRecentSearch({
  variables: { id },
  update: async (cache, payload) => {
    const queryKey = localStorage.getItem('queryKey');
    const queryVars = { query: queryKey }

    const prevQuery = cache.readQuery({ 
      query: QuerySearches, variables: queryVars 
    })
     
    // This is what I want to remove:
    console.log(prevQuery)

    // Based on the linked Medium post,
    // I thought this was it but I guess not.
    await cache.writeQuery({
      query: QuerySearches,
      data: { query: null },
      variables: queryVars
    })

    // I thought it was easy as:
    // delete prevQuery.query ? but nope.

    // This does nothing. The id on "query" is queryKey (ie: 'london')
    cache.modify({
      id: cache.identify(queryKey),
      broadcast: false,
      fields: {
      query(_, { DELETE }) {
          return DELETE;
        },
      },
    })

    // For the RecentSearch, this works:
    cache.modify({
      fields: {
        recentSearches: (searches, { readField }) => {
          return searches.filter(
            ref => id !== readField('id', ref),
          );
        },
      },
    })
    
  }
}).then( _ => refetch());

如果我可以删除 prevQuery,我的问题就会解决。有什么想法吗?

0 个答案:

没有答案