T
TanStack6mo ago
variable-lime

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
absent-sapphire
absent-sapphire6mo ago
Can you use ensureQueryData and await the result? It shouldn't be async because you have data already
variable-lime
variable-limeOP6mo ago
ok, i was doing that, thought they would be an easiest way
absent-sapphire
absent-sapphire6mo ago
Maybe there is. I'd like to know that
hilarious-sapphire
hilarious-sapphire6mo 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
variable-lime
variable-limeOP6mo ago
thats on the component, not the loader
hilarious-sapphire
hilarious-sapphire6mo 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?