T
TanStack10mo ago
multiple-amethyst

useGetUser for auth, but pending state/data doesnt reset

const UserProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const { isPending, error, data } = useGetUser();
const user = data?.user;

if (isPending) return null;

return (
<UserContext.Provider value={{ user }}>{children}</UserContext.Provider>
);
};

export const useUser = () => useContext(UserContext);

export default UserProvider;
const UserProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const { isPending, error, data } = useGetUser();
const user = data?.user;

if (isPending) return null;

return (
<UserContext.Provider value={{ user }}>{children}</UserContext.Provider>
);
};

export const useUser = () => useContext(UserContext);

export default UserProvider;
First question: On the first load of the app, this will error, since there is no access token. Once the user logs in, I am re-calling queryClient.refetchQueries(['user']) This sets isPending back to true, and the screen goes white (on the initial load, we show a loading screen until the root removes it, so the null isnt visible). My understanding was that isPending/isLoading are only true on the first fetch. Is this not true with errors? Second question: Once loggedin and the user is logging out, I call queryClient.invalidateQueries(), which also re-fetches the user query. This failes again, because the user is loggedout, so no access token. However, Im using the 'user' variable in some lower component to 'render a different set of pages (the auth pages'. But only the 'isError' value of useGetUser() updates. The user var is still its old value. Does the response not clear old data if theres an error?
2 Replies
multiple-amethyst
multiple-amethystOP10mo ago
this is the query:
const query = useQuery({
retry: 0,
staleTime: Infinity,
queryKey: ['user'],
queryFn: async () => {
const response = await getUser();
if ('error' in response) throw response;
const user = response.data.user;
// Login to 3rd party services
await qonversion.login(user);
posthog.identify(user._id, { role: user.role });
return response.data;
},
});
const query = useQuery({
retry: 0,
staleTime: Infinity,
queryKey: ['user'],
queryFn: async () => {
const response = await getUser();
if ('error' in response) throw response;
const user = response.data.user;
// Login to 3rd party services
await qonversion.login(user);
posthog.identify(user._id, { role: user.role });
return response.data;
},
});
future-harlequin
future-harlequin10mo ago
Usually for auth, you'd put a session token in a cookie. Query isn't quite the right place for it. And the auth state mostly interacts with your Router instead of query. I would not render any component that requires user authorisated data if the user is not logged in, so I'd redirect back to the login page As for logout, queryClient.reset should do the trick?

Did you find this page helpful?