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•4y ago
I'd use
queryClient.resetQueries();
https://tanstack.com/query/v4/docs/reference/QueryClient#queryclientresetqueriesQueryClient | TanStack Query Docs
QueryClient
The QueryClient can be used to interact with a cache:
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•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 queryforeign-sapphire•4y ago
You'd want queryClient.clear() here
xenial-blackOP•4y ago
I am using useQuery to run the fetch function by the way. Does that affect things?
foreign-sapphire•4y ago
no
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•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-usequeryclientReact Query FAQs
Answering the most frequently asked React Query questions
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!