本文介绍了Apollo Client 从缓存中删除项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将 Apollo 客户端与 React 一起使用.我用许多不同的变量查询帖子.所以我在不同的缓存"中有一篇文章.现在我想删除一个帖子.所以我需要从所有缓存"中删除这个特定的帖子.

Hy I'm using the Apollo Client with React. I query the posts with many different variables. So I have one post in different "caches". Now I want to delete a post. So I need to delete this specific post from all "caches".

const client = new ApolloClient({
    link: errorLink.concat(authLink.concat(httpLink)),
    cache: new InMemoryCache()
});

后查询:

export const POSTS = gql`
    query posts(
        $after: String
        $orderBy: PostOrderByInput
        $tags: JSONObject
        $search: String
        $orderByTime: Int
    ) {
        posts(
            after: $after
            orderBy: $orderBy
            tags: $tags
            search: $search
            orderByTime: $orderByTime
        ) {
            id
            title
            ...
        }
    }
`;

我尝试使用 cache.modify(),它在我的突变中未定义([https://www.apollographql.com/docs/react/caching/cache-interaction/#cachemodify][1])

I tried it with the cache.modify(), which is undefined in my mutation([https://www.apollographql.com/docs/react/caching/cache-interaction/#cachemodify][1])

const [deletePost] = useMutation(DELETE_POST, {
        onError: (er) => {
            console.log(er);
        },
        update(cache, data) {
            console.log(cache.modify())//UNDEFINED!!!
            cache.modify({
                id: cache.identify(thread), //identify is UNDEFINED + what is thread
                fields: {
                    posts(existingPosts = []) {
                        return existingPosts.filter(
                            postRef => idToRemove !== readField('id', postRef)
                         );
                    }
                }
            })
        }
    });

我还使用了 useApolloClient() ,结果相同.

I also used the useApolloClient() with the same result.

感谢任何帮助.

推荐答案

这个选项对我有用

const GET_TASKS = gql`
  query tasks($listID: String!) {
    tasks(listID: $listID) {
      _id
      title
      sort
    }
  }
`;

const REMOVE_TASK = gql`
  mutation removeTask($_id: String) {
    removeTask(_id: $_id) {
      _id
    }
  }
`;

const Tasks = () => {
  const { loading, error, data } = useQuery(GET_TASKS, {
    variables: { listID: '1' },
  });
  сonst [removeTask] = useMutation(REMOVE_TASK);

  const handleRemoveItem = _id => {
    removeTask({
      variables: { _id },
      update(cache) {
        cache.modify({
          fields: {
            tasks(existingTaskRefs, { readField }) {
              return existingTaskRefs.filter(
                taskRef => _id !== readField('_id', taskRef),
              );
            },
          },
        });
      },
    });
  };

  return (...);
};

这篇关于Apollo Client 从缓存中删除项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 12:59