Search code examples
reactjsresponse

if condition is not working in error response


When I tried to check the condition for the response status, it is not even going inside and checking if, what should be done to compare and show the alert. FYI swal is a npm package used for alert

onSubmit(values) {
    this.props.signIn(values, response => {
        if (response.status === 200) {
            swal("Login successful", "Signed In", "success");
            this.props.history.push(`/dashboard/${response.data.user_name}`);
        } else {
            console.log("wrong password");
            swal({
                title: "Invalid Email Id or password",
                icon: "warning"
            });
        }
    });
};

Action.js

export function signIn(values, callback) {
    const request = axios.post(`${ROOT_URL}/${APP_ID}/${API_KEY}/users/login`, values).then(() => callback());

    return {
        type: LOGIN_DETAILS,
        payload: request
    };
}

Solution

  • Need to return axios promise, try with that code

        onSubmit(values) {
        this.props
          .signIn(values)
          .then((response) => {
            swal("Login successful", "Signed In", "success");
              this.props.history.push(`/dashboard/${response.data.user_name}`);
          })
          .catch((error) => {
            console.log("ajax error");
            swal({
              title: "Invalid Email Id or password",
              icon: "warning",
            });
          });
      }