T
TanStack2y ago
xenial-black

Router Context not updating

basically the same problem as here: https://stackoverflow.com/questions/77856598/tanstack-router-how-to-pass-value-from-another-context Setup is a little different because I am using react-query to get the currently logged in user.
export function App() {
const currentUserQuery = useQuery(currentUserQueryOptions);
if (currentUserQuery.isLoading)
return (
<Loader/>
);

console.log("router now has new context:", currentUserQuery.data);
//^ this console log runs only once, and is never called again
return (
<Suspense
fallback={
<Loader/>
}
>
<RouterProvider
router={router}
context={{ currentUser: currentUserQuery.data }}
/>
</Suspense>
);
}
export function App() {
const currentUserQuery = useQuery(currentUserQueryOptions);
if (currentUserQuery.isLoading)
return (
<Loader/>
);

console.log("router now has new context:", currentUserQuery.data);
//^ this console log runs only once, and is never called again
return (
<Suspense
fallback={
<Loader/>
}
>
<RouterProvider
router={router}
context={{ currentUser: currentUserQuery.data }}
/>
</Suspense>
);
}
Even when the query dev tools tell me that currentUserQuery.data has updated, the context still keeps the old values. This means I manually need to add useEffect in the protected routes and redirect users if they are not logged in, since I cannot rely on the context. What am I missing?
Stack Overflow
Tanstack Router - How to pass value from another context
I'm building a react app that is using Tanstack router, and I'd like to access values from a context provider that I created over to the router beforeLoad handler for a given route. My app structure
3 Replies
inland-turquoise
inland-turquoise2y ago
Are all the routes in your app authed? Not a single unauthenticated route? Since it's coming from Query and its store, the reactivity can get lost. You could: 1. Try wrapping the currentUser into useMemo and add currentUserQuery.status and currentUserQuery.data as the deps. 2. In the root route or (preferably) a layout route, you can force the value into the context by tapping the queryClient directly and pulling from its cache. One of these two options should do it for you.
xenial-black
xenial-blackOP2y ago
The login/register pages are unauthenticated, that's where I want to redirect users Will try this, thanks nope, does not work. Can verify, that even memoized, the context does not seem to check. If it means anything, I am trying to check in the beforeLoad method for protected routes. And even when I can verify that curentUserQuery.data is fresh, within the beforeLoad calls, the context is still old.
inland-turquoise
inland-turquoise2y ago
Option 2 then.

Did you find this page helpful?