How to use loader data of a parent route?
I use ensureData in the parent route and return it in the loader, and I want that data to be accessed using useLoaderData in the child routes.
6 Replies
wise-white•2y ago
Are you using an async state management library like React Query or an equivalent?
If so, then do not access the data using the useLoaderData hook. Instead access it using useQuery or an equivalent from the async state management library.
The loader data really is specific to that route. Unlike Route Context that gets merged from parent to child.
Especially considering the examples from the repo, I can't think of a good way you'd access parent loader data from a child route. Maybe use matches()?
correct-apricotOP•2y ago
hey, im using trpc + React Query
I want to use useLoaderData to get the initial data.
with ensureData
I moved the loader to the child routes,
but its a bit of a code duplication.
wise-white•2y ago
If I'm not mistaken, tRPC uses react-query under the hood for the state management aspect of it.
So just call the ensureData method in the parent route, and ONLY access the data using the
.query() or . useQuery() hook.
Do not use the useLoaderData hook here since your data doesn't live in the router, rather in the tRPC+react-query binding.correct-apricotOP•2y ago
In the component, Im using it like this
this is the recommended way to use it (https://trpc.io/docs/client/react/createTRPCQueryUtils)
so, Im looking for a way to get that scheduleData for the initialData, in child routes, when its loaded in the parent.
wise-white•2y ago
Couple things to unpack here:
In the example from the tRPC docs which uses React Router, is that this isn't a parent-child route scenario. That is loading the data for that specific route and returning the data. It isn't being passed down to a child route.
2nd just because you ensureData in the loader, doesn't mean that you have to return that data from the loader and consume it using the useLoaderData hook.
As it says in the docs, it'll fetch and cache the data into react-query and let Query handle the data from there on.
So, don't use the useLoaderData hook and instead just
await the ensureData in the loader and return nothing.
Then when you in your child route just call your query (api.something.somethingElse.useQuery) and that data will already be available in the cache since you would've cached that data in the loader for the parent.
Instead of useQuery you could call the useSuspenseQuery equivalent and it'll absolutely guarantee that the loader data is present.
Loaders get called based on the route hierarchy. So if you've awaited an ensureData in a parent loader, then it'll already be available by the time the child route is rendered.
But you cannot non-trivially access the parent loader's data in a child route.correct-apricotOP•2y ago
hmm okay, thanks!