1

I'm experiencing an issue where the catch block in my signup process is running before the try block. When I attempt to sign up, the catch block displays the error message before the success message is shown. This behavior is unexpected, as I would expect the try block to execute first.

Here is the relevant code snippet:

const onSignup = async (values: any) => {
        try {
          setLoading(true);
          const response = await axios.post(`/api/users/signup`, values);
          const responseData = response.data;
          if (!responseData.error) {
            toast.success("Signup success", successState);
            router.push("/login");
          } else {
            if (responseData.error === "User already exists") {
              toast.error("User already exists", errorState);
            }
          }
        } catch (error: any) {
          toast.error(
            "An error occurred during sign in. Please try again later.",
            errorState
          );
        } finally {
          setLoading(false);
        }
      };
Mayank Kumar Chaudhari
  • 16,027
  • 10
  • 55
  • 122
Jayesh Gadhok
  • 39
  • 1
  • 6
  • `catch` never runs before `try`. Possibly explanations for what you see include that `onSignup` is called multiple times or that your toaster displays messages in the wrong order. So do some debugging what the `values` passed to each call are, and what `error` is thrown. – Bergi Jul 06 '23 at 13:30

1 Answers1

1

In dev mode, this may be happening due to multiple renders - Check out this thread - Why my nextjs component is rendering twice?

So, actually, your catch block is not called twice. The error you see is from the previous render.

Mayank Kumar Chaudhari
  • 16,027
  • 10
  • 55
  • 122