How to invalidate whole cache for Apollo GraphQL (not for one specific query) onclick

1.8k Views Asked by At

What I need is to force all the queries that I have on pages to refetch data after clicking one button.

I have found the soultion for one specific query here (https://www.apollographql.com/docs/react/caching/advanced-topics/), but it's not clear have can I do this for all the queries at one time.

1

There are 1 best solutions below

0
Bergi On

Right on that page you have already linked, there's https://www.apollographql.com/docs/react/caching/advanced-topics/#resetting-the-cache

Resetting the cache

Sometimes, you might want to reset the cache entirely, such as when a user logs out. To accomplish this, call client.resetStore. This method is asynchronous, because it also refetches any of your active queries.

import { useQuery } from '@apollo/client';
function Profile() {
    const { data, client } = useQuery(PROFILE_QUERY);
    return (
      <Fragment>
        <p>Current user: {data?.currentUser}</p>
        <button onClick={async ()=>client.resetStore()}>
            Log out
        </button>
      </Fragment>
    );
}

To reset the cache without refetching active queries, use client.clearStore() instead of client.resetStore().