Suraj Ingle
Suraj Ingle

Reputation: 412

React Apollo client perform multiple mutations that depend on each other

Consider the scenario where the useMutation() hook is used:

  1. Mutation 1 response includes id1
  2. Mutation 2 uses id1 as an input variable along with some other variables.
  3. Mutation 2 responds with id2.
  4. Mutation 3 uses id2 as an input variable.

How do I handle the asynchronous responses? With REST API we could do something like:

try{
  let data1 = await mutation1(...)
  let data2 = await mutation2(data1.id1, ...)  
  let data3 = await mutation2(data2.id2, ...)
}catch(err) => {
  console.error(err)
}

How do I do this with GraphQL, Apollo Client?

Upvotes: 0

Views: 541

Answers (1)

tom hikari
tom hikari

Reputation: 387

With React Saga you could do that like this:

  1. create your mutation function

    export const mutateMethods = async (object: any) => {
       return await apolloClient.mutate({
         mutation: gql`
           ${object}
         `,
       });
     };
    
  2. Create your reducer and action

  3. Create your sagaIterator function

export function* actionSaga(action: any): SagaIterator {
  try {
    const res_0 = yield call(mutateMethods, action.payload);
    const res_1 = yield call(mutateMethods, res_0);
    const res_2 = yield call(mutateMethods, res_1);
    yield put(reducer_action_success());
  } catch (error) {
    yield put(reducer_action_failed());
  }
}
  1. Dispatch the action that will call your sagaAction
dispatch({type:"CALL_MY_MUTATIONS", payload:data})

Upvotes: 1

Related Questions