T
TanStack17mo ago
grumpy-cyan

React Query for sessions not updating all components

I am trying to use React Query in a Next app router app to manage the state of my auth sessions. The problem I'm having is I have multiple client components using the hook but the aren't all updating when I log in or out. I have a navbar component and say a profile component. I login with button of profile. The navbar doesn't update and same for logout. If I refresh page it updates fine. Could anyone check what I need to do. I have tried invalidateQueries which does not work and now using setQueryData but still not having desired effect. https://gist.github.com/rsheppard-dev/3eea3b1b314762c288b0acbd0140091e
Gist
LoginForm.tsx
GitHub Gist: instantly share code, notes, and snippets.
4 Replies
other-emerald
other-emerald17mo ago
I think you have the library basics right, but perhaps the way you export useSession is creating a bad closure? (would verify, but not at a computer) The more common pattern I've seen is to return useQuery... and do the destructuring where the hook is used rather than where it is defined.
grumpy-cyan
grumpy-cyanOP17mo ago
That doesn't work either I'm afraid.
'use client';

import { defaultSession } from '@/utils/defaults';
import { useQuery } from '@tanstack/react-query';

export default function useSession() {
return useQuery<SessionData>({
queryKey: ['session'],
queryFn: () => fetch('/api/session').then(res => res.json()),
initialData: defaultSession,
});
}
'use client';

import { defaultSession } from '@/utils/defaults';
import { useQuery } from '@tanstack/react-query';

export default function useSession() {
return useQuery<SessionData>({
queryKey: ['session'],
queryFn: () => fetch('/api/session').then(res => res.json()),
initialData: defaultSession,
});
}
other-emerald
other-emerald17mo ago
Looks same and familiar to me. I don't have that much to offer without digging deeper (which is impractical for me right now), but a minor remark is that I think you can remove the mutationKey. Not that I necessarily think it hurts (I don't really know what it does), just that I have personally never had a need for one, doing similar things as what you are doing now, and any reduction to the code surface should be helpful for spotting the actual root cause.
grumpy-cyan
grumpy-cyanOP17mo ago
I have removed the mutationKey and tried different things but can not get it to update multiple components consistently. Looking at my dev tools when I login, it shows one instance of 'session' in fetching state. When I logout Devtools shows no instances. When I refresh page manually it shows two instances of 'session' in stale state. When it has 2 instances it works as expected but if I logout it goes back to no instances and login it goes back to one which is obviously not the behaviour i want. I am really stuck on this if anyone has a solution I would be very grateful.
No description
No description
No description

Did you find this page helpful?