I have multiple independent fetch requests located in different files and initiated by useSWR.
How can I know when the last request is done, i.e. there are no pending requests?
I'd like to know the number of active requests initiated by useSWR.
My question is similar to to this jQuery question.
You can just add the other useSWR as a dependent. Let's say you have 2 requests located in 2 files:
// A.js
export function A() {
const { data } = useSWR('/api/a')
return data
}
// B.js
export function B() {
const { data: dependentA } = useSWR('/api/a')
const { data } = useSWR(dependentA ? '/api/b' : null) // start to fetch when A is ready
return data
}
Note that only 1 /api/a request will be initiated, but /api/b will be pending on it.
I was looking for something similar to the react-query which has an interesting useIsFetching hook.
"useIsFetching is an optional hook that returns true if any query in your application is loading or fetching in the background (useful for app-wide loading indicators)."
I think you could code that yourself, using React Context to store an object with the SWR keys as keys and a true if it's loading or false if it's not (or inverted if you want to know if it already loaded), then pass a function to set when a new query starts and ends (set it as true/false), then you can reduce it to a single true/false to know if there is at least one query loading.
Just an idea about how to solve it, right now there is no way to know if there are pending requests.
Just like cache access, having some global APIs might be a good idea. However I think the API should be an event listener, not a hook.
Just like cache access, having some global APIs might be a good idea. However I think the API should be an event listener, not a hook.
It should probably be both – an event bus you can register/unregister listeners with, and a hook that does that for you and causes effects.
Most helpful comment
Just like cache access, having some global APIs might be a good idea. However I think the API should be an event listener, not a hook.