I'm using RTK Query to fetch some data. I need to access the loading state across various components in my application, but I'm unsure how to do so.
I feel like it may simply be that I'm misunderstanding how to utilize RTK Query properly in a larger application. Most of the examples are a single component, and I don't quite see how you can get access to the various states of a single query from various components.
For example, I need to show a loader in a main section of the app where the data is generated from a query. Then, I need to show a completely different loader in a tiny part of a sidebar, which has some content details which is generated via the same API query.
How does this work with RTK Query?
Do any examples exist which use multiple components that share this query state/status?
Am I completely missing a fundamental understanding of how state is used across the app? (I feel this is the thing here haha)
If you call the same useQuery hook with the same arguments in another component, those two will share the cache entry and return exactly the same data - it will not trigger another request to the server.
So: just useQuery everywhere you need it :)
You can also define a selector for that "loading" piece, if you don't wan't to use the query inside every component, like so:
const selectIsResourceLoading = (state: RootState) => apiSlice.endpoints.getResource.select()(state).isLoading;
And then, reuse it within the component:
const isResourceLoading = useTypedSelector(selectIsResourceLoading);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With