I am working on a web based on graphql/apollo/react. So I want to useMutation to make post request, and when completed, I clean up some caches that belows to some queries. I read the doc of apollo, and it guide use to readquery from cache and writequery. But I have three questions:
my sample code:
import type {DataProxy, FetchResult} from 'react-apollo'
import {useMutation} from '@apollo/react-hooks'
const[theMutationQuery] = useMutation(MUTATIONQUERY, {
refetchQueries: [somequery expression] // will the force a rerender of all components that use 'somequery'
onCompleted: () => {},
onError: () => {},
update: (store: DataProxy, data: FetchResult<?*>) => {
const cacheDataForOtherQuery = store.readQuery({
query: GETQUERY1
variables: {
v: "str",
},
// so can i add one more query here?
})
// then how should I clean up the result from readquery, that is, cacheDataForQuery. Also, after cleaning up, will this force a rerender of all components using the query(GETQUERY1 here)
}
});
Can I read multiple queries cache with one client.readquery call? No, you cannot read multiple queries' cache with one client.readQuery() call. You need to call client.readQuery() multiple times, once for each query you want to read from the cache.
If the answer is no, does readquery execute synchronously? Yes, client.readQuery() executes synchronously. It immediately reads the query data from the cache and returns it.
How to clean the query cache (not update) after read them? To clean the cache for a specific query, you can use the client.evict() method. This method takes in a options object with a query property that should be the GraphQL document representing the query you want to evict. This method will remove the query and it's data from the cache.
client.evict({ query: GETQUERY1, variables: { v: "str" } });
will the cache update or refetch(refetch in useMutation) of a query force a re-render of all the components that call the query? Yes, when you update or refetch a query, all the components that are using that query will be re-rendered to reflect the updated data. This is because the Apollo client will notify those components that the data they are using has changed, and they will update their state accordingly.
Regarding your sample code, by using the update function you can manipulate the store's cache, you can use it to update a specific query data, but also you can use it as you did to read a query data and then use the data to update or clean other queries. The refetchQueries option in the mutation configuration is used to refetch a set of queries after a mutation is completed. Keep in mind that refetching a query will cause all components that are using that query to re-render and reflect the new data.