TanStackT
TanStack16mo ago
5 replies
radical-lime

Context-based authentication

Good morning. I'm trying to authenticate with a context following the example from the docs (code below, but there isn't much to see).

I have verified in the context itself that the value isLoggedIn is changing (with a useEffect much like the one in InnerApp below, but obviously in the context itself ). However, although InnerApp is subscribed to the auth context, it never picks up on the change.

It seems I can't use router.invalidate() inside of the context itself without running into errors about the Router context being undefined, but I am running it inside of the Login component when a user successfully logs in. In other words, the router context should be refreshed since it is invalidated on Login (or Logout).

In short, my question is - what can I do to make sure the router context picks up changes to the inner auth context since it does not currently?

const router = createRouter({
routeTree,
notFoundRoute,
// Initialize the auth context undefined - pass it in
context: { auth: undefined! },
});

// Register the router instance for type safety
declare module "@tanstack/react-router" {
interface Register {
router: typeof router;
}
}

function InnerApp() {
const auth = useAuth()
console.log('auth from innerapp', auth.isLoggedIn, auth.isLoading)
useEffect( () => {
(this is where I expect the useEffect to run when the auth context changes, but it never does)
console.log('main: isLoggedIN', auth.isLoggedIn)
}, [auth, auth.isLoggedIn])

return <RouterProvider router={router} context={{auth: auth} } />
}

ReactDOM.createRoot(document.getElementById("root") as HTMLElement).render(
<React.StrictMode>
<AuthProvider>
<InnerApp />
</AuthProvider>
</React.StrictMode>
);
Was this page helpful?