Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit `react-hook-form` properly with a `react-query` mutation?

I use react-query in combination with react-hook-form. In order to activate the isSubmitting prop on form and show loading state while submitting, the mutate function needs to return a Promise instead of using mutate directly.

For now my workaround is as follows:

const { mutate } = useMutation(...);

const update = (data) => {
    return new Promise((resolve, reject) => {
      mutate(data, {
        onSuccess: resolve,
        onError: reject,
      });
    });
};

and then pass update to methods.handleSubmit comming from form.

Could anyone share some experience on this topic? Thanks!

like image 813
Nadezhda Serafimova Avatar asked Mar 12 '26 02:03

Nadezhda Serafimova


1 Answers

In order to activate the isSubmitting prop on form and show loading state while submitting, the mutate function needs to return a Promise instead of using mutate directly.

seems like this is a requirement of react-hooks-form?

You can use mutateAsync, which will return a Promise, and pass that to react-hook-form

Other than that, useMutation also returns an isPending state for your mutation, so you could let react-query handle that (I don't know react-hooks-form, so not sure if that's possible).

like image 163
TkDodo Avatar answered Mar 14 '26 12:03

TkDodo