Loading data in router using tanstack-query but need api token from react hook
I'm looking to load some data within my routes using the
loader
method. However, my scenario is that accessing my API server requires a JWT token and the only method I have available for that is a react hook. Since the loader isn't a react component, I can't straightforwardly call my getToken()
method from there.
I'm keen on being able to do this so if anyone has any suggestions I'd appreciate hearing them. For one thing, I'd need this in order to do any data loading via the router. For another, my current use case is that I need to load data in the router so that I can dynamically populate my breadcrumb trail. The idea is that when accessing the path /entity/{id}
, the router can look up the relevant entity by its id and display e.g. its name or title in the breadcrumb trail. In principle, this can work (see e.g. https://github.com/TanStack/router/discussions/895). But not being able to access the getToken()
method is currently preventing me from doing this in the most obvious way.
For context, I'm using axios to handle my API calls and I have a useEffect()
in my root route (routes/__root.tsx
) which adds an interceptor to my axios instance which calls getToken()
and then adds it to the axios request as an authorization header. This works for regular uses of useQuery
within my react components and pages. But I can't figure out how to make it work in the router's loader
method. Any ideas would be much appreciated!2 Replies
passive-yellow•14mo ago
you can pass hooks into the router context using RouterProvider
correct-apricot•14mo ago
I had no idea, that's great! https://tanstack.com/router/latest/docs/framework/react/guide/router-context#how-about-using-react-contexthooks
Router Context | 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...