T
TanStack2y ago
optimistic-gold

How to get router context in component?

Hi I have a isAuthenticated value in my router context, but I want to render either Component 1 or Component 2 based on whether we are logged in. How can I do this? I'm new to react so any help would be appreciated thank you!
11 Replies
rare-sapphire
rare-sapphire2y ago
you should be able to do Route.useRouteContext() or you can pass down specific values from the context through the loader
optimistic-gold
optimistic-goldOP2y ago
Is there a way for me to get the context in component? when I create the route
export const Route = createRootRouteWithContext<MyRouterContext>()({
component: (context) => {
<RootComponent />
},
})
export const Route = createRootRouteWithContext<MyRouterContext>()({
component: (context) => {
<RootComponent />
},
})
maybe someothing like this?
rare-sapphire
rare-sapphire2y ago
yes, by doing this
export const Route = createRootRouteWithContext<MyRouterContext>()({
component: () => {
const context = Route.useRouteContext();

return <RootComponent />
},
})
export const Route = createRootRouteWithContext<MyRouterContext>()({
component: () => {
const context = Route.useRouteContext();

return <RootComponent />
},
})
optimistic-gold
optimistic-goldOP2y ago
ahh I see thank you. could you also show me how to access it in loader and pass down. would appreciate it
rare-sapphire
rare-sapphire2y ago
export const Route = createRootRouteWithContext<MyRouterContext>()({
loader: ({ context }) => ({ context });
component: () => {
const { context } = Route.useLoaderData();

return <RootComponent />
},
})
export const Route = createRootRouteWithContext<MyRouterContext>()({
loader: ({ context }) => ({ context });
component: () => {
const { context } = Route.useLoaderData();

return <RootComponent />
},
})
optimistic-gold
optimistic-goldOP2y ago
can the component be async?
rare-sapphire
rare-sapphire2y ago
No, Tanstack Router does not support RSCs at least, not as of now
optimistic-gold
optimistic-goldOP2y ago
I see. Well this makes it a bit difficult for me. I'm building this app in tauri and I'm using a local storage library however the get method for the storage is asynchronous and I was hoping that I could route based on a value stored there, but not sure if this is possible now?
rare-sapphire
rare-sapphire2y ago
What do you mean "route based on a value stored there"?
optimistic-gold
optimistic-goldOP2y ago
I have a session token that the user gets on login. So i want to check for the sesion token when rednering the component I guess I could do it in the loader and then pass it down to the component to check
rare-sapphire
rare-sapphire2y ago
You can take a look at tanstack query as well

Did you find this page helpful?