#How to access data of parent loader?

27 messages ยท Page 1 of 1 (latest)

sick canopy
#

My index route loader fetches some data. But I cannot use it inside child route.
indexRoute.useLoader() throws the following error error:

const routeTree = rootRoute.addChildren([
  indexRoute.addChildren([
    resourcesRoute,
    resourceDetailsRoute,
    resourceCreateRoute,
    resourceUpdateRoute,
  ]),
  loginRoute,
]);

How can I access parent route loader result?

boreal parcel
#

From my experiments:

a) When using data inside a component being rendered by current route, you can retrieve it with myRoute.getLoader(). Preferably myRoute.getLoader(myRoute.useRouteContext().loaderOptions).

b) When using data inside a component being rendered by a subroute, you cannot access the data directly from the loader itself with myRoute().getLoader(). You just get an error. However, you can access the data using useLoaderInstance({key: 'myLoaderKey'}).

signal gull
#

You can use the useLoaderInstance if you are also using a Loader constructor

If you just want to reference a parent loader, I believe you can import the useLoader hook from "tanstack/react-router" and then use it like this

const data = useLoader({ from: "/parentPath" })
lost zodiac
#

This doesn't work for me, same error

night veldt
#

please provide a minimal complete example, e.g. by forking on of the existing examples on stackblitz

candid ruin
outer trail
#

not an expert but the error goes away for me if I add a trailing slash:

const data = useLoaderData({ from: '/posts/' });

after all, your route is defined as:

but yeah there seems to be a /posts/ and a /posts route ๐Ÿค”

#

also, since you are using query - why not get access with useQuery ?

night veldt
#

@outer trail is absolutely right, if you are inside of /posts/, then use this as from

#

however, the loader seems to be in /posts

#

so that's the parent

#

you could use the useParentMatches hook to access data from the parent

outer trail
#

so posts.tsx creates /posts but posts.index.tsx creates /posts/ ?

night veldt
#

yes

#

if you don't have any children routes of /posts, you don't need the index route

#

but if you have, and you want to render something at /posts/without any further path segments, you need the index route

outer trail
#

and posts.tsx is always rendered, like route.tsx inside a posts directory?

#

k, sorry for the confusion, I've only worked with nested directories until now

night veldt
#

posts.tsx is at the same level as posts directory.
the same thing is route.tsx insides of posts directory

#
โ”œโ”€โ”€ posts
โ”‚ย ย  โ””โ”€โ”€ index.tsx
โ””โ”€โ”€ posts.tsx
#

or

#
โ””โ”€โ”€ posts
    โ”œโ”€โ”€ index.tsx
    โ””โ”€โ”€ route.tsx
```
candid ruin
night veldt
#

how about useSuspenseQuery?

candid ruin
#

I must have missed that hook. Will try that out. Thanks.

#

But regarding the Invariant Failed error. Is useLoaderData not the way to load parent loader data?

night veldt
#

no it is not