Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apollo GraphQl react. How to clear query cache for all variable combinations?

I am using apollo graphql in my react application. Say I have the following query:

query ListQuery($filter: String!) {
   items(filter: $filter) {
     id
     name
   }
}

This query lets me query a list of items using a filter. Say I used filter string A, and then used filter string B. The cache would now contain two entries: ListQuery(A) and ListQuery(B).

Now let's say I use a mutation to add a new item. How can I remove all the cached queries from the cache? So in this case, I want to remove both ListQuery(A) and ListQuery(B) from the cache.

How can I accomplish this?

like image 877
Andy Hansen Avatar asked May 19 '17 22:05

Andy Hansen


4 Answers

In your case, you can use the apollo's method client.resetStore();

It will clear the previous cache and then load the active queries.

like image 134
Nitin Avatar answered Nov 13 '22 08:11

Nitin


Seems like what you need is refetchQueries option/prop to be set to array of query names strings. The documentation states that:

If options.refetchQueries is an array of strings then Apollo Client will look for any queries with the same names as the provided strings and will refetch those queries with their current variables.

So as an example for using graphql HOC you could try to do:

function SomeComponent(props) {    const performMutation = () => {     props.doStuff({ refetchQueries: ["ListQuery"] })       .then(/* ... */)       .catch(/* ... */)   }    return (/* ... */) }  export default graphql(DO_STUFF, { name: "doStuff" })(SomeComponent) 

Or with the Mutation component:

function SomeComponent(props) {   return (     <Mutation       mutation={DO_STUFF}       refetchQueries={mutationResult => ["ListQuery"]}>       {(doStuff, { loading, error }) => {         /* ... */       }}     </Mutation>   ); } 

If this is somehow doesn't do what you need, there is also a workaround using update option.

Hope this helps.

like image 42
streletss Avatar answered Sep 22 '22 05:09

streletss


Try this:

 query ListQuery($filter: String!) {
       items(filter: $filter) {
         id
         name
       }
    },
    fetchPolicy: 'no-cache'

More here: https://www.apollographql.com/docs/react/caching/cache-interaction/#bypassing-the-cache

like image 3
Giang Van Avatar answered Nov 13 '22 09:11

Giang Van


Try evicting the particular query object from the cache...

cache.evict({ id: "ROOT_QUERY", fieldName: "listQuery" });
cache.gc();

I got this working after reading this: https://danreynolds.ca/tech/2020/05/04/Apollo-3-Client-Cache/

like image 1
Danoz Avatar answered Nov 13 '22 09:11

Danoz