How can I access the data of the query called in the parent component, inside a child component without prop drilling.
For example, if in parent.js I call the getPost
query
const {data} = useGetPostQuery();
then how can I access this data further down the hierarchy?
There are two options I see:
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
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
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