devrnt / react-use-wizard

🧙 A React wizard (stepper) builder without the hassle, powered by hooks.

Home Page:https://devrnt.github.io/react-use-wizard/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to catch the errors?

matepaiva opened this issue · comments

Hi, first of all, I would like to thank you for your amazing job!

I am throwing an error in an async function that is wrapped by the handleStep and it works fine to avoid going to the next step. The only problem is that I don't know where I could catch the error to treat it and avoid bubbling it up.

This is a simplification of my implementation:

function WizardStep() {
  const { handleStep, nextStep } = useWizard();

  handleStep(async function handleSubmit() {
    const hasError = await submitToApi();

    if (hasError) {
      throw new Error('submit_error');
    }
  });

  return <Form onSubmit={nextStep} />;
}

In the example above, if I try-catch inside of handleSubmit, the handleStep will not catch it. So where should I try-catch?

Thank you!

Hi, thanks really appreciate it! 👍

The thrown errors in the handleStep are rethrown so they can be caught when nextStep is called. You'll need to explicitly await nextStep to catch the errors.

So you should be good with:

...
return (
    <Form
      onSubmit={async () => {
        try {
          await nextStep()
        } catch (error) {
          // Catch `handleStep` errors here
        }
      }}
    />
  );

I'll close this, if you have any more question, don't hesitate to re-open

Hi, @devrnt! Sorry for the late response. I got it and it works super well! Thank you :)