There are two options I see:
- The "right" answer way - is to use a selector from API slice to access the cached data which is already in rtk-q's Redux store. Let's say we have
posts
API slice definition. So we'll be able to access some particular cached post directly with a selector, provided by rtk-q:
.
const selectPost = posts.endpoints.getPost.select(postId);
selectPost
- is a memorized selector, gererater by rtk-q for a particular postId
. To fetch the data - that you'll need to pass the app state in, and it will return the expected post from the cache, that your parent component fetched before.
Inside the component it can be used with useSelector
like:
const { data: post } = useSelector(posts.endpoints.getPost.select(postId));
Some more details here:
https://redux.js.org/tutorials/essentials/part-8-rtk-query-advanced#selecting-users-data
- And a pretty straightforward way - is just to use the same query code in your child :).
Even it sounds weird\smelly - there is nothing wrong with it, due to you making your component standalone\decoupled, and it will get this data anyway - even will be used outside the parent component. But if it will be used in a case you described, as a child - it will just fetch data from the cache, with no real API call, so with no harm to performance. And it looks even more clear than selectors.
I prefer exactly this approach, and I feel it keeps the code more consistent - I'm just declaring that "I need that data" in a component, and don't care if it was fetched before or not, keeping all the components decoupled from knowing about any others component, making it cohesive.
It's somehow touched here:
https://redux.js.org/tutorials/essentials/part-8-rtk-query-advanced#cache-data-subscription-lifetimes
Offtopic bonus: In a case when you don't need the post
data on a parent's component and want to fetch it only to improve responsiveness - you may use the usePrefetch
hook. For example - on the "Edit" button hover, it will make an API call, put the data in the cache, so post
will be available for children instantaneous.
More here:
https://redux-toolkit.js.org/rtk-query/usage/prefetching