Is there a way to use hooks in loader function?
I have set up an useAxios hook for bearer token, however I am unable to use that in loader functions, is there a workaround for this?
For now, I have saved the token in router context, and I am passing that to a custom fetcher to avoid sending auth header explicitly for every request.
6 Replies
constant-blue•17mo ago
We'll need a reproduction to understand the issue you are facing.
constant-blue•17mo ago
You can get started using https://stackblitz.com/github/tanstack/router/tree/main/examples/react/quickstart-file-based
StackBlitz
Router Quickstart File Based Example - StackBlitz
Run official live example code for Router Quickstart File Based, created by Tanstack on StackBlitz
eager-peachOP•17mo ago
Thanks for getting back, the issue is quite simple and obvious, hope this helps.
https://stackblitz.com/edit/github-w9sknq?file=src%2Froutes%2Findex.tsx
https://stackblitz.com/edit/github-w9sknq?file=src%2Froutes%2Findex.tsx
Mounis Bhat
StackBlitz
Router Quickstart File Based Example - StackBlitz
Run official live example code for Router Quickstart File Based, created by Tanstack on StackBlitz
constant-blue•17mo ago
Ohhh. What you are trying to do is using a hook outside of React. Its why its failing.
Since, you may be better off, creating your axios instance outside of React and passing it around using context.
https://stackblitz.com/edit/github-w9sknq-cjatzg?file=src%2Fmain.tsx
Sean Cassiere
StackBlitz
Router useAxios for @mounis - StackBlitz
Run official live example code for Router Quickstart File Based, created by Tanstack on StackBlitz
constant-blue•17mo ago
You could ofc get your useAxios to a workable state, but you need to have a way of passing your values into context.
But you absolutely have to follow the Rules of React, and not try to invoke a hook outside of a React component/hook (lifecycle essentially).
constant-blue•17mo ago
We call this out in this portion of the docs.
https://tanstack.com/router/latest/docs/framework/react/guide/authenticated-routes#authentication-using-react-contexthooks
It may be worth adding in the Router Context section as well 🤔
Authenticated Routes | TanStack Router React Docs
Authentication is an extremely common requirement for web applications. In this guide, we'll walk through how to use TanStack Router to build protected routes, and how to redirect users to login if they try to access them.
The route.beforeLoad Option