Cristian Riță
Cristian Riță

Reputation: 559

React Query execute mutation after query is fetched

Let's say I have a query, useFetchUser() and a mutation, useMutateUser(). When my component is rendered I want to fetch the current user and then execute the mutation after the query completion. So I have something like this:

   const {data} = useFetchUser()
   const {mutate} = useMutateUser()

   useEffect(() => {
      if(data) {
        mutate() 
     }
   }, [data, mutate])

Now when I check in the network tab I see that the mutation starts while the query is still pending. What am I doing wrong?

Upvotes: 1

Views: 2403

Answers (1)

hg.ricardo
hg.ricardo

Reputation: 41

You can send react-query options to your hook useFetchUser() in params and take advantage of onSuccess callback:

const useFetchUser = (options = {}) => {
    return useQuery(yourKey, () => fetchUser(), {...options})
}

And consume like this:

const {mutate} = useMutateUser()
const {data} = useFetchUser({onSuccess: mutate()})

Upvotes: 1

Related Questions