I you can't use async/await return a promise

Sat Oct 09 2021

Try to adapt to the project's standards

Maybe this is an edge case, but working with react-hook-foorm (a library made for React that does a lot of wonderful things like knowing whether your form is submitting or not) I ran into this problem, and my Tech Lead at that time gave me a genius solution, it was obvious but I wasn’t capable of seeing it.

So, the library looks for a promise when you submit, that way as long as the promise is not resolved, the property isSubmitting of the form will be true, pretty handy if you need that flag, in my case I needed it to disable the submit button so the user won’t click twice and make 2 requests to the backend.

Here is kinda the initial code

import { useForm } from "react-hook-form";

const SubmitButton = () => {
  const { handleSubmit, isSubmitting } = useForm();
  const onSubmit = handleSubmit(async (form) => {
    await apiCall();
  });
  return <></>;
};

There is not apparently problem with the code above, but there are two, first, by using the async syntax the isSubmitting flag was not working as intended, it will disable the button and enable again instantly, while the API call still in process, so the button was clickable while the request was still alive. And second, it did not match our project’s standard which was to use the apiCall.then() method of a promise to resolve it, so the code above ended up not being approved to merge, my TL then suggested to return a promise and remove the async syntax. It resulted to be exactly what I needed for my ticket, so it looked like this at the end.

import { useForm } from "react-hook-form";

const SubmitButton = () => {
  const { handleSubmit, isSubmitting } = useForm();

  const onSubmit = handleSubmit((form) => {
    return apiCall().then((response) => {
      console.log("It worked!");
    });
  });

  return <></>;
};

This obviously is not the way to go all the times, is just a solution that fits with the requirements and is always better to have options when solving problems.