Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
  );
};
like image 780
Aidos Omurzakov Avatar asked Mar 30 '26 23:03

Aidos Omurzakov


1 Answers

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))
}
like image 112
Fred Nguyen Avatar answered Apr 02 '26 13:04

Fred Nguyen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!