T
TanStack•4y ago
xenial-black

Clearing information on logging off.

Hello. I am using useQuery in a react application. How do I reset everything including error states and such? I want to add that to a logout function.
9 Replies
wise-white
wise-white•4y ago
QueryClient | TanStack Query Docs
QueryClient The QueryClient can be used to interact with a cache:
xenial-black
xenial-blackOP•4y ago
It's not working. import { useQuery, useMutation, QueryClient, QueryCache } from "react-query"; const queryClient = new QueryClient(); const useLogout = () => { const { setAuth } = useAuth(); const logout = async () => { setAuth({}); queryClient.resetQueries(); queryClient.invalidateQueries("employees"); try { // eslint-disable-next-line const response = await axios.post('/users/logout', { withCredentials: true }); // eslint-disable-next-line } catch (err) { } } return logout; } export default useLogout also queryClient.resetQueries("employees"); queryClient.invalidateQueries("employees");
wise-white
wise-white•4y ago
You probably want to use const queryClient = useQueryClient() inside the useLogout hook, otherwise it's resetting a completely different query client than the rest of your app uses If that works, I don't think you'll need that invalidate anymore, the reset should apply to every query
foreign-sapphire
foreign-sapphire•4y ago
You'd want queryClient.clear() here
xenial-black
xenial-blackOP•4y ago
I am using useQuery to run the fetch function by the way. Does that affect things?
foreign-sapphire
foreign-sapphire•4y ago
no
xenial-black
xenial-blackOP•4y ago
I'm guessing I have somehow defined different queryClient variables then. I did move the one outside of logout hook to inside it. but there is also const queryClient = new QueryClient() in index.js How can I consolidate those? There is also queryClient inside the DataContext file.
foreign-sapphire
foreign-sapphire•4y ago
- there should only be one querClient - you should access it via const queryClient = useQueryClient() see also: https://tkdodo.eu/blog/react-query-fa-qs#why-should-i-usequeryclient
React Query FAQs
Answering the most frequently asked React Query questions
xenial-black
xenial-blackOP•4y ago
That may be the solution to my problem. I'll try to finish work quickly so I can get back to react as soon as possible and try this. @TkDodo 🔮 I think it worked. I'll confirm later. Thank you!

Did you find this page helpful?