简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM