Handling queries when fetch function parameter change but you want the cache to remain
Hey guys,
My use case goes like this, I'm using react-query to build a package for managing flags (could be feature flags or flags for ab-testing).
This package is used as a shared dependency in micro-frontend environment (meaning multiple applications are basically using the same query cache).
This works really nice and everything is in sync.
Sometimes different app will look at the same flag but with different options that needs to be sent to the server. If I include this options as part of the queryKey, it will basically treat it as 2 separate cache instances (which is good for most cases but not for me for this one).
How would you advise doing this?
Removing the options from the queryKey and manually sending them to the queryFn?
And also, sometimes I need to refetch with different options (but still using the same cache). I see that refetch doesn't support this at the moment.
Thanks in advance
4 Replies
ratty-blush•3y ago
Does the api return the same data regardless of the options that are provided? If so, how are the options used?
genetic-orangeOP•3y ago
Hey Julien
Yes, the API basically returns the same data, the options are for letting the server know if the user actually made an impression regarding this flag (This is how the API works, not something which is under my control. You basically can retrieve data on a flag, and you can also call the same api with different options which means that you don't only want the flag data but also want an analytic impression to be made)
sunny-green•3y ago
Hi 👋
Refetch will never support this. Refetch does what the name suggests (refetches a query). If you're changing the query, it's a different query.
If you could explain why it making a new query is undesirable then I can probably suggest an approach 🙂
ratty-blush•3y ago
I would probably still put the extra options in the query key. If you want to preserve the cache, you could probably call
setQueriesData inside onSuccess to update the "sister" queries.
It won't be able to read from the cache when using new options though, that'll trigger the actual API call (but probably wanted if the goal of the extra options is to record analytics?).