So, I am working on a project's feature that allows users to view data based on different variables, for example, data that are unique to years, location, gender etc.
Below is the code that I write:
this._querySubscription = this._apollo.watchQuery({
query: *some graphql query*,
variables: {
// this is where the variables are dump
}
})
.valueChanges
.subscribe(( { data, loading } ) => {
do something with the data
})
Now, don't worry about the error with the function and stuff because I have got everything right. I even have below code to handle cache and even evict.
let cache = this._apollo.client.cache as InMemoryCache
let data = this._apollo.client.cache.readQuery({
query: *some graphql query*,
variables: { *using the same variables as the writeQuery, of course*}
})
cache.evict({
fieldName: "*the fieldname from the query*",
broadcast: false,
});
this._apollo.client.cache
.writeQuery({
query: *some graphql query which is the same as above*,
data,
variables: {
*again, same variables*
}
})
Some of the things that I have come across are:
- Without using the
readQueryandwriteQuery, when running thewatchQueryagain, even with different variables to run the query will return the same data from the cache. - Using the
readQuery,writeQuery,evictand running the second query with different variables will not return the same data from the cache (which I am looking for) but, if I try to run the first query back, the data return will be empty, probably because I modify the cache. 3.If you are thinking of usingfetchPolicywhen running the query, I have tried all 4fetchPolicy,cache-first,network-onlyetc. It works if I usecache-network-onlybut then somehow I have no idea how to wait for it completely finish making the request and updating the cache before I can update my UI.
I had the same problem as well when using Apollo. They way I solved was to create a separate module that handle all the Graphql stuff with a Factory, and a
no-cacheon the.watchQuerymethod. I'm sure you can changefetchPolicyto accept one of these values:'cache-first' | 'network-only' | 'cache-only' | 'no-cache' | 'standby' | 'cache-and-network'(Values take fromwatchQueryOptions.d.ts).I'm using the latest version of the packages:
So, here's the module:
tsconfig.jsonfile needs to be edited with these versions by adding this line:"allowSyntheticDefaultImports": trueundercompilerOptionsThen I call the query in a component: