T
TanStack2y ago
sensitive-blue

Using `navigate` in a providers handler before RouterProvider instance

The docs describes an example for passing a context into the Router (https://tanstack.com/router/latest/docs/framework/react/guide/authenticated-routes#authentication-using-react-contexthooks). I have a very similar situations to this, however in my situation I need to leverage the router within a callback of the provider. Building on the example from the docs, my situation would be equivalent to this:
function InnerApp() {
const auth = useAuth();
return <RouterProvider router={router} context={{ auth }} />;
}

function App() {
return (
<AuthProvider
onLogin={(redirectTo) => {
router.navigate({ to: redirectTo }); // ❌ router not ready here!
}}
>
<InnerApp />
</AuthProvider>
);
}
function InnerApp() {
const auth = useAuth();
return <RouterProvider router={router} context={{ auth }} />;
}

function App() {
return (
<AuthProvider
onLogin={(redirectTo) => {
router.navigate({ to: redirectTo }); // ❌ router not ready here!
}}
>
<InnerApp />
</AuthProvider>
);
}
What would be the appropriate way of solving this? 1. Nest multiple RouterProvider – haven't seen this documented, so unclear if possible 2. Save the callback value(s) to state and pass to InnerApp -> RouterProvider for use within root beforeLoad 3. ??? Thanks!
Authenticated Routes | TanStack Router 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
0 Replies
No replies yetBe the first to reply to this messageJoin

Did you find this page helpful?