Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to invalidate react-query whenever state is changed?

I’m trying to refetch my user data with react-query whenever a certain state is changed. But ofcourse I can’t use a hook within a hook so i can’t figure out how to set a dependency on this state.

Current code to fetch user is:

const {data: userData, error: userError, status: userStatus} = useQuery(['user', wallet], context => getUserByWallet(context.queryKey[1]));

This works fine. But I need this to be invalidated whenever the gobal state wallet is changed. Figured I could make something like

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

useEffect(
    () => {
        useQueryClient().invalidateQueries(
            { queryKey: ['user'] }
        )
    },
    [wallet]
)

but this doesn’t work because useQueryClient is a hook and can’t be called within a callback.

Any thoughts on how to fix this?

General idea is wallet can change in the app at any time which can be connected to a different user. So whenever wallet state is changed this user needs to be fetched.

thanks

>Solution :

useQueryClient returns object, which you can use later.

For example:

const queryClient = useQueryClient()

useEffect(
    () => {
        queryClient.invalidateQueries(
            { queryKey: ['user'] }
        )
    },
    [wallet]
)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading