Suppose it stores cache about item id = 5 and it does not go to server to fetch data. But what if data on server changes for item id = 5, then how would apollo cache know that the data on server changed ?
Is there any interval at which apollo cache makes requests to server to know if data on server has changed ?
As cool as it would be for the cache to know if data changed on the server, unfortunately it’s not that magic . Apollo Client determines when to refetch based on the data in your cache and the query you are trying to execute. Assuming you’re using a fetchPolicy that utilizes the cache, the query is going to try and look up every field in the cache, and if the data is all there, it will pull that data from the cache and return it (no network request). If any or all of those fields are missing from the cache, then the query will execute a network request to load that data from the server to give you a complete response.
Unfortunately there is no great way for a client to know if a server has updated data without asking for that data again. This is one of the limitations of the request/response model. Without a persistent connection to the server and having the server push that data to the client (possible with Websockets), your client will only ever be able to determine if there is fresh data by asking for the data again.
With Apollo, there isn’t a refetch that happens automatically after a query has been executed, however there are a couple ways you can make sure you can get updated data. You can manually call refetch yourself (useful if you have a UI element that triggers refresh), or you can setup your query to use polling, which will execute a network request at a set interval.
Something else to mention is that because Apollo uses a normalized cache, you gain some advantages when it comes to getting fresh data in your queries. For example, if a mutation is executed and returns updated data for a record in the cache, any query that returns that record is going to get that updated data (you can see an example of this in our docs). You can also write to the cache directly, which also has the same effect: any query that returns that record will be automatically updated.
I thought similar that if we wanted to have data to be in sync (with the real world), then cache might not help here. Instead, to choose subscriptions over the cache which may suit the use-case I am targeting for.
Yes! Subscriptions would give you the best shot at keeping “real time” data when you need it since the server can push updates to the client. Hope you’re able to find success with that approach!