Hongli Bu
Hongli Bu

Reputation: 561

How to refetch/fetch after a series of mutation in graphql/apollo/react

Right now I have a use case to use two useMutations to create/update database. So the second one is depends on the success of the first one. And also the second mutation needs to be called in a loop, just think about that I have a array and I need loop through the array and apply the second mutation.

After all these mutation finished I have to refetch another api to update caches, because the cache would be impacted by the two mutations.

I am really struggling with how to achieve this.

From another post: Apollo Client - refetchQueries after multiple updates I can do probably like

const [creatEnrollment] = useMutation(mut1)
const [updateEnrollment] = useMutation(mut2)
const [toFetch, {loading, error, data}] = useLazyQuery(UsersDocument)

await Promise.all([creatEnrollment(), updateEnrollment()])
const result = () => toFetch({
   variables: {name: 'i'}
})

but the problem is 1. I need to execute second mutations after the first one; 2, I need to have an array that applied to second mutations one by one.

I also saw here How can I wait for mutation execution in React Query?

we can use onSuccess

const mutate1 = useMutation((data) => axios.post('/something', { data }))
const mutate2 = useMutation(somethingResult) => axios.put('/somethingElse', { somethingResult })

<button onClick={() => {
    mutate1.mutate('data', {
      onSuccess: mutate2.mutate
    })
}} />

But still 1. how to loop thru mutate2.mutate? and how to fetch after mutate2 finished do like this????:

<button onClick={() => {
    mutate1.mutate('data', {
      onSuccess: mutate2.mutate
    })
    mutate2.mutate('data', {
      onSuccess: query
    })
}} />

Thank you for helping!!

Upvotes: 0

Views: 3339

Answers (1)

Tejashree Surve
Tejashree Surve

Reputation: 121

You can have a function for useMutation and onSuccess the data which use get on success use other mutation

const mutationFuntion = (id) => {

 // this is first mutation
  return useMutation(
    (newTitle) => axios
      .patch(`/posts/${id}`, { title: newTitle })
      .then(response => response.data),
    {
      // 💡 response of the mutation is passed to onSuccess
      onSuccess: (data) => {
       // call the api which will get all the latest update
      },
    }
  )
}

Get the Data of first mutation

  const [addTodo, { data, loading, error }] = mutationFuntion(//send data);

This is consecutive mutation I found it from this https://react-query-v3.tanstack.com/guides/mutations#consecutive-mutations doc

 useMutation(addTodo, {
   onSuccess: (data, error, variables, context) => {
     // Will be called 3 times
   },
 })
 
 ['Todo 1', 'Todo 2', 'Todo 3'].forEach((todo) => {
   mutate(todo, {
     onSuccess: (data, error, variables, context) => {
       // Will execute only once, for the last mutation (Todo 3),
       // regardless which mutation resolves first 
     },
   })
 })

For handle the promise of every mutation call

 const mutation = useMutation(addTodo)
 
 try {
   const todo = await mutation.mutateAsync(todo)
   console.log(todo)
 } catch (error) {
   console.error(error)
 } finally {
   console.log('done')
 }

Please you need to verify on what kind of object you want to call mutation in loop it array or some thing alse.

Upvotes: 1

Related Questions