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

Time:12-01

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!!

CodePudding user response:

can you try this way?

const {data} = mutate1.mutate('data') mutate2.mutate('data', { enabled: !!data })

CodePudding user response:

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),
    {
      //            
  • Related