T
TanStack3y ago
ambitious-aqua

Typesafe context for FileRoute

Hi, Is there any way to make the route context typesafe with the new FileRoutes? I followed the TanStack Query tutorial (https://tanstack.com/query/latest/docs/react/examples/react/react-router), adding the beforeLoad, loader and pendingComponent properties to the route config, but when I try to request the context inside component like this:
const { queryOptions } = useRouterContext({ from: "/plan" });
const { queryOptions } = useRouterContext({ from: "/plan" });
I get an IDE error "Property 'queryOptions' does not exist on type 'RouteContext'.". There is a generic property TContext, but it's at the end of the list of generic properties (and I don't want to redefine all properties). Is there any way for TanStack Router to infer the data returned by beforeLoad or is there any way I can explicitly define it, without redefining a dozen other generic values? Data returned by validateSearch is being properly infered, and inside the loader function, the search parameter is properly typed as { id: string } Code snippet:
export const route = new FileRoute("/plan").createRoute({
component: () => {
const { queryOptions } = useRouterContext({ from: "/plan" }); // Error here - TS2339
return (...);
},
beforeLoad: ({ search }): { queryOptions: ... } => {
...
return {
...,
queryOptions: {...},
};
},
validateSearch: (search: Record<string, unknown>): { id: string } => {
...
},
loader: async ({ search, context }) => {
await queryClient.ensureQueryData((context as any).queryOptions);
},
pendingComponent: () => <Text>Loading...</Text>,
});
export const route = new FileRoute("/plan").createRoute({
component: () => {
const { queryOptions } = useRouterContext({ from: "/plan" }); // Error here - TS2339
return (...);
},
beforeLoad: ({ search }): { queryOptions: ... } => {
...
return {
...,
queryOptions: {...},
};
},
validateSearch: (search: Record<string, unknown>): { id: string } => {
...
},
loader: async ({ search, context }) => {
await queryClient.ensureQueryData((context as any).queryOptions);
},
pendingComponent: () => <Text>Loading...</Text>,
});
TanStack Router version: 0.0.1-beta.174
React Query React Router), Example | TanStack Query Docs
An example showing how to implement React Router), in React Query
1 Reply
fair-rose
fair-rose3y ago
encounter this issue as well, it seems like it is not supported yet

Did you find this page helpful?