1

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?

2
  • hard to say without knowing what the custom hooks are doing. since data will be undefined for as long as the query is initially loading, your condition prevents the mutation from running. Generally, I would put side effects into the onSuccess callback of the query. Commented Jul 2, 2021 at 14:46
  • You should debug with console logs inside the useEffect, you could console log isLoading and data fro example. Commented Jul 4, 2021 at 14:53

1 Answer 1

1

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()})
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.