Currently, I am implementing a feature in my project that allows users to access and analyze data based on various parameters such as year, location, and gender.
Below is the code snippet that I have developed for this feature:
this._querySubscription = this._apollo.watchQuery({
query: *insert specific GraphQL query here*,
variables: {
// here we define the necessary variables for the query
}
})
.valueChanges
.subscribe(( { data, loading } ) => {
perform actions with the retrieved data
})
No need to fret about any errors related to function implementation as everything has been carefully set up. In fact, I also have additional code to manage cache handling and eviction.
let cache = this._apollo.client.cache as InMemoryCache
let data = this._apollo.client.cache.readQuery({
query: *specific GraphQL query*,
variables: { *using the same variables as defined above*}
})
cache.evict({
fieldName: "*field name from the query*",
broadcast: false,
});
this._apollo.client.cache
.writeQuery({
query: *specific GraphQL query matching previous*,
data,
variables: {
*reuse same variables*
}
})
Throughout the process, I have encountered some key observations:
- Re-running the
watchQuery
without utilizingreadQuery
orwriteQuery
will result in fetching the same cached data even when different variables are provided. - On the other hand, employing
readQuery
,writeQuery
, andevict
before executing a new query with altered variables prevents retrieving the same data from the cache. However, attempting to re-run the initial query afterwards may lead to an empty dataset due to potential modifications made to the cache. - If considering the use of
fetchPolicy
, experimenting with all available options likecache-first
andnetwork-only
revealed satisfactory outcomes withcache-network-only
. Nevertheless, ensuring completion of request and cache updates before UI modification remains a challenge.