Home > Software design >  else statement is ignored in react
else statement is ignored in react

Time:04-21

when i am trying to perform this task to change password, everything works fine if the response is 200 and it also gives me the pop up window, but if its not it dosent perform the else statement,it like no else. completely ignored.

here is the code

const submitForm = () => {

    let form_data = new FormData();
    form_data.append('old_password', formValues.oldpass);
    form_data.append('new_password', formValues.newpass);
    try {
        axios.put(baseUrl   '/change-password/', form_data,
            {
                headers: {
                    'Authorization': `Token ${token}`
                }
            }


        ).then((response) => {
            const Swal = require('sweetalert2');
            console.log(response.data);
            if (response.status === 200) {

                Swal.fire(
                    'Great!',
                    'Password updated successfully',
                    'success'
                )
            }
            else {
                alert('error ', 'password has not been changed !!');
            }

        });
    } catch (error) {
        console.log(error);

    }
};

please help i am new to react and i`ve had this issue for days.

CodePudding user response:

Axios throws the response if the status code is something else than 2xx. Which means that if you get e.g. 4xx or 5xx the then clause is not run. Instead you need a catch clause that will handle this case.

.then((response) => {
    const Swal = require('sweetalert2');
    console.log(response.data);
    Swal.fire('Great!', 'Password updated successfully', 'success')
}).catch((response) => {
    alert('error ', 'password has not been changed !!');
    console.log(error);
});

In this case you can remove try-catch as it won't catch any errors.

Optionally you can await the result of the axios call to have the current catch clause catch the error. Then you'll also need the function to be async.

const submitForm = async () => {
    let form_data = new FormData();
    form_data.append('old_password', formValues.oldpass);
    form_data.append('new_password', formValues.newpass);
    try {
        await axios.put(baseUrl   '/change-password/', form_data,
            {
                headers: {
                    'Authorization': `Token ${token}`
                }
            }
        ).then((response) => {
            const Swal = require('sweetalert2');
            console.log(response.data);
            Swal.fire('Great!', 'Password updated successfully', 'success')
        });
    } catch (error) {
        console.log(error);
        alert('error ', 'password has not been changed !!');
    }
};

https://axios-http.com/docs/handling_errors

  • Related