Cache invalidation; refetch practices when nothing says the data has changed, but it might have?

178 views Asked by At

While learning about GraphQL and Apollo, I went through this tutorial series.

It shows how to create an application, that has:

  • A channel list view (/)
    • Shows all channels
    • Allows to open up channel detail view
    • Allows to create new channel
  • A channel detail view (ie. /soccer)
    • Shows messages added to channel
    • Allows user to add a new message

Apollo by default caches queries and that presents an issue:

  1. open channel (/soccer), for the first time, data is not present in cache, query is executed and result stored in cache
  2. go back to channel list view
  3. open a different channel (/baseball)
  4. other visitor adds a message for /soccer
  5. go back to channel list view
  6. open channel (/soccer), due to data being present in store - stale data gets loaded, because nothing says the data is stale and should be refetched

I cannot seem to find a reasonable way to tackle it. Not looking for code, just some good practices on how to handle it with GraphQL.

I tried changing fetchPolicy to cache-and-network, but it doesn't ask for more data - same applies, nothing says the data is stale. network works, but that goes around cache - a viable solution when it fits the requirements, but I actually wan't some caching.

Possible options I have thought of:

  • Separate queries: one for main channel details, one for messages. Set messages fetchPolicy to network. Viable option, but sends already available data around.
  • Separate queries. Messages are being paginated. Upon loading determine if first load or not and fetchMore.
  • Utilize a GraphQL subscription that notifies about server side events, use that to determine if should refetch. Introduces loads of other nuances, for instance, how long should I listen to events for channel X if I have already left it.

I know it depends on the project, but what other options are out there, which are favored, why?

0

There are 0 answers