Forcing an error state without an unnecessary refetch #7679
Unanswered
lucas-barake
asked this question in
Q&A
Replies: 1 comment 3 replies
-
Is it possible to check if the token exists first, like this: function useMeQuery() {
const [token] = useAuthToken();
const hasToken = token !== '';
const meQuery = useQuery({
// ...
enabled: hasToken,
});
return [meQuery, hasToken] as const;
}
const AuthWrapper = ({ children }) => {
const [meQuery, hasToken] = useMeQuery();
if (!hasToken || meQuery.isError) {
return <SignIn />;
}
if (meQuery.isLoading || meQuery.isPending) {
return <PageSpinner />;
}
return children;
}; And logout would be like this: function useLogoutAction() {
const [, setToken] = useAuthToken();
const queryClient = useQueryClient();
return useCallback(() => {
setToken('');
queryClient.removeQueries({
queryKey: [...], // meQuery queryKey
exact: true,
});
}, [setToken, queryClient])
} When the user logs out, the token will be cleared, causing |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
Long story short, I realized that instead of hooking up an external state management solution (e.g. Zustand) to persist the data I get from, for example, a
/me
query, I could do it all within TanStack Query.I have an
AuthWrapper
component like this one:The idea is, the
useMeQuery
determines whether the user is authenticated or not. If the query results inisError
, that means they are not authenticated, hence I render theSignIn
component. If it'ssuccess
, then I know the user is authenticated.What I'd usually do here is persist the session data with an external store, and if I want to logout, all I'd need to do is remove the data, and the
AuthWrapper
would already "redirect" the user to theSignIn
component.So, I realized that, instead of hooking two state management solutions together, I can use the
useMeQuery
for everything. So far, it's working as expected, except that I can't find an elegant solution to have thelogout
functionality.I guess I could reset the query, but then I'd have no way to trigger an error to prompt
AuthWrapper
to renderSignIn
. And the query will just end up fetching again, making an unnecessary extra HTTP request.Is this flow possible? Or is this something out for reach for TanStack Query? Thanks!
Beta Was this translation helpful? Give feedback.
All reactions