TanStackT
TanStackโ€ข2w agoโ€ข
3 replies
verbal-lime

Get root context in any component, but it is overridden by each route in beforeLoad

Example:
There is a <Header> component used in __root.tsx, that requires data/information, that can be overridden by each route individually thanks to
beforeLoad
.

useRouteContext({ from: "__root__" }) gets the context defined in the
beforeLoad
of __root.tsx, but not what is overridden by the route itself.

Basically, I want to get the context defined already in the root route, but if it is overridden by a route, get that instead.

We could do that, it seems to work (but doesn't seem efficient)
const matches = useMatches()
matches.at(-1)?.context?.items ?? []

// or maybe better?
const items = useMatches({
  select: (matches) => {
    return matches.at(-1)?.context?.items ?? []
  },
})


I tried useMatch, from what is in the docs (https://tanstack.com/router/latest/docs/framework/react/api/router/useMatchHook), it says:
opts.from, Optional, but recommended for full type safety.

But it doesn't seems true, as it is required in TypeScript.

const match = useMatch({
  from: "__root__",
  select: (match) => {
    return match.context.items
  },
})

Same issue as for the useRouteContext, it gets the data defined in the
beforeLoad
of __root.tsx, and not what is overridden by each route.

Another question, not really related, but it's part of what I'm trying to solve. I would like to return an array of "items" containing "to"/"link" information.

I tried the ToOptions:
export interface RouterContext {
  queryClient: QueryClient
  items: Array<{ to?: ToOptions; children: string }>
}

But it doesn't seem serialisable or possible to return it from a
beforeLoad
.

I also tried LinkOptions, using the linkOptions function and such, and each time, TypeScript is not happy about it.
Was this page helpful?