TanStackT
TanStack10mo ago
3 replies
homeless-violet

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:
export function useUser(): UserContext {
    const queryKey = queryKeys.auth.postLogin
    const { data, status } = useQuery<unknown, Error, AppUserWithRolesPreferences>({
        queryKey,
    })
    const initialized = status !== "pending"

    console.log("user changing", status, data)

    return {
        user: data || undefined,
        initialized,
        queryKey: queryKey,
    }
}


And I'm passing this to my router context like so:
const App = () => {
    const userContext = useUser()
    const queryClient = useQueryClient()

    return <RouterProvider router={router} context={{ user: userContext, queryClient }} />
}

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 ?
Was this page helpful?