graphqlapolloapollo-clientapollo-cache-inmemory

GraphQL: how does Apollo client caching work to keep data consistency with the server?


I'm using apollo-client with apollo-cache-inmemory.

Suppose I have 2 pages: Item List page and Item Detail page.

Item List page displays (by fetching the data using client.query(...):

When navigating to Item Detail page of Item B, I mutate Item B by using the mutation technique involving store.readQuery and store.writeQuery described here: https://www.apollographql.com/docs/react/caching/cache-interaction/#updating-after-a-mutation

Now, before navigating back to the Item List page, suppose that another user of my app did mutation to Item A.

My questions:

  1. When I navigate back to Item List page, do I get the data from the cache or from the server? Does the client.query(...) always fetch data from the server? 🤔

  2. If I got the data from the cache, how can I then keep data consistency with the server? (the goal is to always show updated item, e.g. Item A, in the list - synced with the server while optimizing caching)


Solution

  • If you want to keep the data synchronized even when it's changed by other users, you'll need to either always fetch from the server or implement subscriptions on both server and client. This way you'll be able to push new events when the data changes and have clients subscribe to these changes to keep their caches updates in real time.