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

Viewed 2558

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!

2 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 isLoading 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).

simply use following code

const {register , handleChange , Errors} = useForm();

const {mutation , mutationAsync , isLoading , isError} = useMutation(postData);

const Submit = (data) => {
mutateAsync(data);
}

return(
<form onSubmit={handleChange(Submit)}>
<input type="text" register={'name'}/>
</form>
)
Related