Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access data in child component of query called in parent component in rtk query?

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?

like image 527
Beginner Avatar asked Oct 20 '25 09:10

Beginner


1 Answers

There are two options I see:

  1. 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

  1. 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

like image 196
Eugene Tusmenko Avatar answered Oct 22 '25 01:10

Eugene Tusmenko