Context with query not updating
Hey guys,
I'm testing Tanstack router in addition to Tanstack query.
To manage my user (with authent), I made a hook that looks like this:
And I'm passing this to my router context like so:
And my goal is to use it in
beforeLoad
, trigger the query to update the userContext, and redirect user to auth if not logged, or homepage if logged (the whole app is only available when logged).
The problem is, even by adding a await context.queryClient.ensureQueryData({ queryKey: context.user.queryKey })
on top of my beforeLoad (even tried to put it in loader instead), the userContext does not update, and it doesn't redirect.
My ultimate goal would be that whenever you are in the app, if the user query is triggered and the state change for X reason (session expiration, profile deleted, ...), I want the user to be automaticly redirected to the logged or logged out page in consequence. beforeLoad doesn't seems to fit this goal. Do you have any suggestion ?3 Replies
genetic-orangeOP•5mo ago
Should i create a real react context in addition to this hook to make it reactive ?
flat-fuchsia•2mo ago
@DollarNavalex Did you ever figure this out? I'm having, what I think is, a similar problem but with Clerk. I'm passing a hook into the router context, but the context isn't updating reactively when the hook is called. The only way around it that I've found is to have a useEffect where I'm passing that context in that will invalidate the context whenever the hook's state changes.
provincial-silver•2mo ago
Your beforeLoad/loader won’t re-run when context changes, they only run on navigation.
Since the query client is a stable value, you can isomorphically access the authenticated user in your before load without relying on reactivity when a navigation occurs, otherwise you should handle reactive state inside react components.
For example, you don’t need a reactive value in before load, since this never runs reactively, so you can just call fetch directly:
const user = await queryClient.fetchQueries(userQueryOptions);
before load or loader will never run reactively, you need to put some code in your authenticated/unauthenticated route that will redirect when state changes. This can just be a “Navigate” component that renders when user is not authed.
Otherwise, a stack blitz repro may help point out where the issue is, because using an ensureQueryData should definitely guarantee that when before load runs, you have your user data