karolis2017
karolis2017

Reputation: 2415

How do I refetchQueries when query is called using useLazyQuery hook?

I have a feed list component and I have a search input above it component. Both components use the useLazyQuery hook. const [getFeedPosts, { data, loading, error }] = useLazyQuery(GET_ALL_POSTS) In the feed list, I manually trigger the getFeedPosts on mount and rendering a list of items. In the search input component, I trigger getFeedPosts on click.

Is there a way I can override the cache after I receive results from the search? Ideally, the list component would re-render automatically.

The issue is that useLazyQuery doesn't provide "refetchQueries" function so I can not "refetch" after I get search results.

Otherwise, I would need some global state (redux, context API...) but from then on I have to manage the state manually if I like/update/delete post.

Upvotes: 3

Views: 1666

Answers (1)

karolis2017
karolis2017

Reputation: 2415

Solved this by finding out that useLazyQuery provides the client that I can use to update the cache manually.

const [getPosts, { data, loading, error, fetchMore, client }] = useLazyQuery(GET_ALL_POSTS, {
    onCompleted: (data) => updateCache({ client, data }),
});

function updateCache({ client, data }: any) {
  client.writeQuery({
    query: GET_ALL_POSTS,
    data: {
      ...data,
      post: {
        ...data.post,
        getFeedPosts: {
          ...data.getFeedPosts,
          edges: [...data.post.getFeedPosts.edges],
          totalCount: data.post.getFeedPosts.totalCount,
          __typename: data.post.getFeedPosts.__typename,
        },
        __typename: data.post.__typename,
      },
    },
  });
}

Upvotes: 2

Related Questions