Sunstrike527
Sunstrike527

Reputation: 607

How to make a dependent mutation in react query?

I have a mutate function which make POST request and receives id , after then I need Immediately call next mutation function to make a purchase in accordance with this id, how do I make this ?

const mutation = useCreatePaymentMethodMutation();

const handleSubmit = async(values:any) {
  const form = await mutation.mutateAsync({
    values,
    hash
  })
  return form
}

useCreatePaymentMethodMutation is imported from @Hooks

const useCreatePaymentMethodMutation = () => {
 return useMutation(
    ({ values, accessHash }: { values: any; accessHash: string }) =>
      createPaymentMethodRequest(values, accessHash),
    {
      onSuccess: (data) => {
        // usePayMutation(data.data, accessHash); error. I need to use data after 1st mutation in next 
        request
        console.log("on success data ", data);
      },
    }
  );
}

UPD 1

Here is my usePayMutation method

const usePayMutation = () => {
  return useMutation(({ data, id }: { data: any; id: string }) =>
    payRequest(data, id)
  );
};

Upvotes: 10

Views: 19720

Answers (2)

Fred Nguyen
Fred Nguyen

Reputation: 325

There're 2 options for you to do it

Option 1: In your useCreatePaymentMethodMutation hooks

const useCreatePaymentMethodMutation = () => {
 const mutatePay = usePayMutation()
 return useMutation(
    ({ values, accessHash }: { values: any; accessHash: string }) =>
      createPaymentMethodRequest(values, accessHash),
    {
      onSuccess: (data) => {
        mutatePay(data.id)
      },
    }
  );
}

Option 2: In your handleSubmit function

const mutatePay = usePayMutation()

const handleSubmit = (values:any) => {
  return mutation.mutateAsync({
    values,
    hash
  }).then(data=> mutatePay(data.id))
}

Upvotes: 7

TkDodo
TkDodo

Reputation: 28733

you would create two different mutations, and call them one after the other:

const createPayment = useCreatePaymentMethodMutation()
const otherMutation = useOtherMutation()

const handleSubmit = async(values:any) {
  try {
    const form = await createPayment.mutateAsync({
      values,
      hash
    })
    await otherMutation.mutateAsync(form.id)
  }
  catch(...)
}

Upvotes: 7

Related Questions