T
TanStack9mo ago
vicious-gold

Getting access to parent route data in child route loader

using file-based router, how would you get access in a child route loader, to the parent route data (loader) i.e
const parentRoute = createFileRoute('/dashboard')({
loader: async () => {
const data = await fetch('....')
return data;
},
component: () => <Outlet />, // Ensure child routes can render here
});
const parentRoute = createFileRoute('/dashboard')({
loader: async () => {
const data = await fetch('....')
return data;
},
component: () => <Outlet />, // Ensure child routes can render here
});
`
const childRoute = createFileRoute('/dashboard/settings')({
loader: () => {
const parentData = ???
},
});
const childRoute = createFileRoute('/dashboard/settings')({
loader: () => {
const parentData = ???
},
});
`
6 Replies
protestant-coral
protestant-coral9mo ago
Can you use ensureQueryData and await the result? It shouldn't be async because you have data already
vicious-gold
vicious-goldOP9mo ago
ok, i was doing that, thought they would be an easiest way
protestant-coral
protestant-coral9mo ago
Maybe there is. I'd like to know that
quickest-silver
quickest-silver9mo ago
You might use useChildMatches or useLoaderData
useChildMatches({
select: (matches) => {
const match = matches.find((match) => match.routeId === "/dashboard/settings")
match?.loaderData
},
});
useChildMatches({
select: (matches) => {
const match = matches.find((match) => match.routeId === "/dashboard/settings")
match?.loaderData
},
});
const data = useLoaderData({
from: "/dashboard/settings",
});
const data = useLoaderData({
from: "/dashboard/settings",
});
both url are typesafe
vicious-gold
vicious-goldOP9mo ago
thats on the component, not the loader
quickest-silver
quickest-silver9mo ago
oh my bad, I misread it 🙏 returning the data in paren't beforeLoad instead of loader would be an option? in that case you can use router context
Router Context | TanStack Router React Docs
TanStack Router's router context is a very powerful tool that can be used for dependency injection among many other things. Aptly named, the router context is passed through the router and down throug...

Did you find this page helpful?