TanStackT
TanStack2y ago
7 replies
accused-moccasin

How to configure router with queryClient in context?

I'm interested in using the router to load/pre-load data via react-query. The example code at "How about an external data fetching library? (https://tanstack.com/router/latest/docs/framework/react/guide/router-context#how-about-an-external-data-fetching-library) is:
import { createRootRouteWithContext, createRouter, } from '@tanstack/react-router' interface MyRouterContext { queryClient: QueryClient } const rootRoute = createRootRouteWithContext<MyRouterContext>()({ component: App, }) const queryClient = new QueryClient() const router = createRouter({ routeTree: rootRoute, context: { queryClient, }, })

However, the tanstack-router quickstart/installation instructions (https://tanstack.com/router/latest/docs/framework/react/installation) direct you to configure these things in different files i.e. the createRouter method should go into main.tsx while the createRouteRoute (which is analogous to createRootRouteWithContext) goes into routes/__route.tsx. And if I try to separate them naively, with the MyRouterContext interface being defined in routes/__root.tsx to go with createRootRouteWithContext, I get a warning with the definition of createRouter in main.tsx because it depends on the MyRouterContext interface defined in another file.

So, I think we need better instructions on how to actually do this. When you want to add queryClient to the router context, what do you need in main.tsx and what do you need in routes/__root.tsx? Thanks in advance for any pointers.
You can install TanStack Router with any NPM package manager.

`sh
Installation | TanStack Router React Docs
TanStack Router's router context is a very powerful tool that can be used for dependency injection among many other things. Aptly named, the router context is passed through the router and down through each matching route. At each route in the hierarchy, the context can be modified or added to. Here's a few ways you might use the router context...
Router Context | TanStack Router React Docs
Was this page helpful?