T
TanStack2mo ago
like-gold

Shared context for a route and its children.

Hi, this might be a stupid question but i am kinda lost. Is there a way i can pass the MenuID to my page that is within the layout? I am looking for a TanStack router way of doing so. My global context.
export const Route = createRootRouteWithContext<{
auth: Auth;
queryClient: QueryClient;
}>()({
export const Route = createRootRouteWithContext<{
auth: Auth;
queryClient: QueryClient;
}>()({
In my Layout i set the state for selectedMenuId with a TAB component
export const Route = createFileRoute("/app/_admin/menu/_menu")({
component: RouteComponent,
beforeLoad: async ({ context }) => {
if (context.auth?.user?.restaurant === "") {
redirect({
to: "/app",
});
}
},
});
....
const [selectedMenuId, setSelectedMenuId] = React.useState<
string | undefined
>();
export const Route = createFileRoute("/app/_admin/menu/_menu")({
component: RouteComponent,
beforeLoad: async ({ context }) => {
if (context.auth?.user?.restaurant === "") {
redirect({
to: "/app",
});
}
},
});
....
const [selectedMenuId, setSelectedMenuId] = React.useState<
string | undefined
>();
In my child route i want to access that selectedMenuId. Is there a some smart way of doing so? Similiary i access the user.
export const Route = createFileRoute("/app/_admin/menu/_menu/denni/")({
component: RouteComponent,
});

function RouteComponent() {
const { user } = Route.useRouteContext();

const { data: menuItems, isLoading: menuItemsIsLoading } = useQuery(
getMenuItems({
menuId: menuData?.id,
restaurantId: user.restaurant,
}),
);
export const Route = createFileRoute("/app/_admin/menu/_menu/denni/")({
component: RouteComponent,
});

function RouteComponent() {
const { user } = Route.useRouteContext();

const { data: menuItems, isLoading: menuItemsIsLoading } = useQuery(
getMenuItems({
menuId: menuData?.id,
restaurantId: user.restaurant,
}),
);
2 Replies
like-gold
like-goldOP2mo ago
I forgot to mention that the menuId will often change so i just cant have it in URL parh
fair-rose
fair-rose2mo ago
if denni is a child component, you can add a context for example wrapping the Outlet in the parent and share the state like that "accessing" means you need to "listen" to changes, so keep in mind that this will cause a re-render to child, but you can use the useReducer hack to optimize renders if you want

Did you find this page helpful?