T
TanStack3y ago
fair-rose

Cannot remove "roles" on logout. Only works if refreshed.

I'm trying to clear "roles" since I'm fetching from my backend to authorize the flow to certain routes based on the role. When the user clicks "log out," I'm running the following code:
const invalidateCredentials = () => {
queryClient.removeQueries();
queryClient.clear();
userTokenStore.setState({ role: '', isLoggedIn: false, token: '', storeId: '' })
localStorage.removeItem("user-auth");
return <Navigate to="/login" replace />;
};
const invalidateCredentials = () => {
queryClient.removeQueries();
queryClient.clear();
userTokenStore.setState({ role: '', isLoggedIn: false, token: '', storeId: '' })
localStorage.removeItem("user-auth");
return <Navigate to="/login" replace />;
};
The problem is that if I try to log in with a user with a different role, the same role remains. But if I log out, reload, and log in with the other user, it works. How can I make this work?
7 Replies
other-emerald
other-emerald3y ago
If you remove queries and there are observers, they will be refetched again. So first log out and then clear the cache
conscious-sapphire
conscious-sapphire3y ago
⬆️ not quite true, strictly speaking. removeQueries removes queries from the cache, that's it. If you have active observers, they will have to trigger a fetch on the next render, but removeQueries itself doesn't trigger a render.
fair-rose
fair-roseOP3y ago
How is it possible to actually perform what I'm trying to do without having to trigger a render? Maybe the best approach for this would be to just have a regular request made without React Query?
conscious-sapphire
conscious-sapphire3y ago
your code shown should work. removeQueries and clear is redundant because clear calls removeQueries. But if you're telling me that you're still seeing queries in the cache e.g. via the devtools after you've called clear, I'd need to see a codesandbox reproduction because I highly doubt that
fair-rose
fair-roseOP3y ago
No, what's actually happening is that when I log out from a user that has a role "super-admin" and then try to log back in with a user with the role "shop" for some reason, react query displays that the request returned "super-admin" again. It's quite odd, since when I log out, everything seems to get cleared from React-Query. I checked the backend, and everything works okay on that side.
conscious-sapphire
conscious-sapphire3y ago
the devtools show what's in the cache, it's the single source of truth. if they are empty, the cache is gone next step: look at what the request returns from the browser; there could be http cache headers involved that return data from the browser cache if that's the case, it's a backend issue
fair-rose
fair-roseOP3y ago
okay, got it! I'll check it now thank you 😄

Did you find this page helpful?