SWR pattern within one query
I have two data sources for the same query/API endpoint. One cached, potentially stale but very quick to access, and another one, remote and fresh, etc. The idea is I would be OK with stale data but would refresh it in the background from the fresh data source. I wouldn't need to show a loading state as long as there's stale data around.
The behavior I'd want on an empty QueryClient store:
1. Load from the fast data store
2. Render with it (contentful)
3. If the above response is stale, load from the remote data store
4. Re-render with the latest data
And if I have data in the QueryClient already:
1. Render immediately using the most fresh version available, regardless of what data store it came from
2. If the data was stale, load from the remote data store
3. Re-render with the latest data
On fetch error, I would want to know about the error state but also use the most recent version of data I have.
I've been thinking about how to best realize this with react-query. I could make some custom
Or if I wanted to fold it into the same query from the perspective of react-query, I could possibly capture the QueryClient in my
I've also considered
Is there a paved path to something like this? Ideally I'd just use a battle tested pattern and get the benefits for free, just like with everything else thanks to react-query
.
The behavior I'd want on an empty QueryClient store:
1. Load from the fast data store
2. Render with it (contentful)
3. If the above response is stale, load from the remote data store
4. Re-render with the latest data
And if I have data in the QueryClient already:
1. Render immediately using the most fresh version available, regardless of what data store it came from
2. If the data was stale, load from the remote data store
3. Re-render with the latest data
On fetch error, I would want to know about the error state but also use the most recent version of data I have.
I've been thinking about how to best realize this with react-query. I could make some custom
useQuerySWR hook that would run two different queries (but always at least one enabled query) and mix in the output depending on what's available and if the cached data is stale. Or if I wanted to fold it into the same query from the perspective of react-query, I could possibly capture the QueryClient in my
queryFn, return cached data from the promise but also spawn another promise against the fresh data source (if the cached version was stale) and call setQueryData directly. But then I'd run into trying to make this work with all the timing parameters and query state that react-query tracks.I've also considered
placeholderData but I didn't grasp the full lifecycle of it, I think it gets reset when queryFn throws an exception?Is there a paved path to something like this? Ideally I'd just use a battle tested pattern and get the benefits for free, just like with everything else thanks to react-query