3

I use the react-query library to get my data. When the user changes, I would love it if the previous user data was removed automatically & new data was fetched.

This does, not happen though, the api gets called a couple times more with the old userId, and only after 1 or 2 times re-focussing on the app, it will fetch the data with the proper new userId. Here is the hook: When I log some info in the getData function, I can see it being called a couple times with the old userId after logging out.

export default function useData() {
    const {user} = useAuth();
    const queryClient = useQueryClient();
    useEffect(() => {
        queryClient.removeQueries('data')
        queryClient.invalidateQueries()
    }, [user]);
    return useQuery('data', () => getData(user!.uid), {
        enabled: !!user,
    })
}

Does anyone know how I can remove all data when my user changes?

1 Answer 1

7

All dependencies of your query should be in the query key, because react-query automatically refetches when the key changes. This is also in the docs here.

In your case, this means adding the user id:

useQuery(
  ['data', user?.uid],
  () => getData(user!.uid),
  {
    enabled: !!user,
  }
)

For clearing up old cache entries, I would possibly suggest setting cacheTime: 0 on your query, which means they will be garbage collected as soon as the last observer unmounts. Calling queryClient.removeQueries manually is also an option.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.