-
I want to force refetch authenticated user after login but Here is example log for the code bellow, Login form submit handler: const onSubmitLogin = async ({ email, password }: AuthFormData) => {
const response = await signIn('credentials', { // signIn() is from next-auth
email,
password,
redirect: false,
});
if (response.ok) {
await queryClient.invalidateQueries([QueryKeys.ME]);
await queryClient.refetchQueries([QueryKeys.ME]); // refetch me
await router.push(response.url);
}
}; Query hook and fetcher function: const getUser = async (id: string) => {
// id is undefined, getUser() is never triggered with updated id
console.log('id', id);
if (!id) return null;
const { data } = await axiosInstance.get<ClientUser>(`${Routes.API.USERS}${id}`);
console.log('data', data);
return data;
};
export const useMe = () => {
const { data: session, status } = useSession();
const id = session?.user?.id;
// id is valid here but () => getUser(id) is not called again with it
console.log('useMe id', id, 'status', status);
const query = useQuery<ClientUser, AxiosError>([QueryKeys.ME], () => getUser(id), {
enabled: status !== 'loading',
onError: (error) => {
console.error('me query error: ', error.response);
// id exists but not valid session, clear it
if (id && error.response.status === 404) {
signOut();
}
},
}); |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
if you want to fetch before you do the redirect, I would do that with |
Beta Was this translation helpful? Give feedback.
invalidateQueries
does a refetch already, however, it will refetch with the old id, because the userId is not part of the query key. I would:["Me", id]
as querykeyremoveQueries
on["Me"]
after successful login to remove all data from other usersuseMe
if you want to fetch before you do the redirect, I would do that with
queryClient.prefetchQueries