Is there a way to detect when data used by a query is evicted from the Apollo Client cache? Is there a way to detect when data used by a query is evicted from the Apollo Client cache? reactjs reactjs

Is there a way to detect when data used by a query is evicted from the Apollo Client cache?


There are two answers here, what is the standard practice way to do this? And how can we possibly make this Better Way?

Standard Practice

https://www.apollographql.com/blog/when-to-use-refetch-queries-in-apollo-client/

Apollo on their blog and on their documentation state that if you mutation has side effects outside of the returned query then you must use an update function if you want to maintain cache consistency. This is similar to using refetchQueries but is more explicit as you are doing the updating of the cache yourself (it also takes less network requests). Although, you are right that this approach will lead to coupling between your transaction's mutation update and all other dependent components.

I believe the best way to structure it would then be to define an update function for all components whose mutation has side effects. And then transaction would call all components update functions that it effects. And these in turn would call their own dependencies. This could get messy so let us see if you could do the cache control yourself.

The Better Way

https://www.apollographql.com/docs/apollo-server/data/data-sources/#using-memcachedredis-as-a-cache-storage-backend

I don't believe you can check the Apollo cache for if data is present, but you could check a Redis cache for this same information and Apollo allows you to plug in other cache implementations. You could even write your own cache implementation and use Redis as a backend to your implementation. This would allow you the finer control over the cache that you want. But, this comes at a massive upfront engineering cost.

Conclusion:

Since your side effects seem to be within the transaction and account components (only two components), I would say you should write a custom update function for now. Once you have a more complex cache coherency problem I would think about diving into a custom caching implementation.