Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why my try catch block won't execute ? – React

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
  };

>Solution :

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);
  }
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading