Home > Net >  Why my try catch block won't execute ? - React
Why my try catch block won't execute ? - React

Time:08-09

I have a register modal which has 3 step.

Fill up the info, getActivate Code and Success Message.

I Want when user filled to inputs and clicked the submit button if there is no error move to next Step but if there is error then React Toastify will show the message.

My problem is why try catch block in MyComponent dosen't work ?

P.S: I'm using Formik and Yup

httpService

const handleExpectedError = (response: any) => {
  if (response?.status >= 400 && response?.status < 500) {
    const errors = response?.data?.errors;
    const errPropertyName: string[] = Object.keys(errors);
    toast.error(errors?.[errPropertyName?.[0]]?.[0]);
  }
};

export const handleRegister = async (user: User): Promise<void> => {
  try {
    await axios.post(`${config.apiEndPoint}/auth/register`, user, header);
  } catch ({ response }) {
    handleExpectedError(response);
  }
};

MyComponent

  const [step, setStep] = useState(1);
  const formik = useFormik({
    initialValues: {
      firstName: "",
      lastName: "",
      email: "",
      phoneNumber: "",
      password: "",
    },
    onSubmit: (value) => {
      if (terms) {
        handleNextStep(value);
      }
    },
    validationSchema: registerSchema,
  });
  // Event Handler 
  // Value below is a referance to Formik object 
  const handleNextStep = async (value: any) => {
    if (step === 1) {
      try {
        await handleRegister(value);
        setStep(step   1);
        await handeGetActivateCode({ email: value.email });
      } catch (error) {
        setStep(1);
      }
    }
    if (step !== 1) return setStep(step - 1);
  };

CodePudding user response:

In httpService file, you have used try-catch. In that catch you are trying to get the error in the curly braces, instead of doing like that if you do the following thing. then the catch block will work fine

export const handleRegister = async (user: User): Promise<void> => {
  try {
    await axios.post(`${config.apiEndPoint}/auth/register`, user, header);
  } catch (response) {
    handleExpectedError(response);
  }
};
  • Related