Reputation: 569
I am building a real-time application using React, Apollo and GraphQL. My plan was that a component will issue a query and then subsequently depend on subscriptions to keep the client cache consistent with backend data in real time. However, I don't believe this will work because I will have to unsubscribe from the subscription when the component is unmounted. When the component is mounted again, the results will be fetched from the query cache and so they will actually be out of date because all the changes that happened in between will be missed since subscription was off. Also turning on the subscription again will mean that the results will get messed up since the changes have been missed in between.
For e.g., in component A, if I have a query:-
query {
customers {
id
name
phoneNo
}
}
and a subscription:-
subscription customersUpdated {
customersUpdated {
id
name
phoneNo
}
}
The customers
query runs when A gets mounted for the first time. The results are cached. All changes to customers data are recorded with the help of subscription customersUpdated
. Note that the subscription doesn't return all customers but just the changes that need to be merged into the query cache. When A is unmounted, I unsubscribe from the subscription. Let's say 5 changes are made to the customers data by another user while A stays unmounted for our current user. When A is mounted again, those 5 changes have been missed and the query just fetches results from the cache. The subscription starts again but now the data is in a bad state since we have missed those 5 changes and won't get them ever!
What is the correct pattern for using subscriptions here? I am trying to avoid time based refetching using the query since I want the application to work in real time. Also in real time, I just want to pull the changes instead of pulling all the data unnecessarily.
Upvotes: 0
Views: 1044
Reputation: 6147
There are a few things you can do:
network-only
or cache-and-network
fetch policy on your GraphQL queries, so that you get up to date data when your component mounts. Initialize the subscription as usual.However, I would encourage you to think more about which parts of your app actually need to be realtime. In most apps, only a small part of the experience needs to have low-latency data updates, so it might be a better strategy to use subscriptions only in small cases. At the end of the day it's often easier to reason about the scaling of a stateless architecture.
Upvotes: 1