0

As I mentioned in the title, I want to show an alert showing if the action was successful or not. But when the alert is supposed to show an error it shows success. When I checked the error variable it says undefined but when I checked it by showing it on the website with JSX it showed the error and not undefined. I'm using redux-thunk

My Code:

loginScreen.js

dispatch(login(email, password)).then(() => error ? alert(error) : alert("success"));

loginAction.js

try {
    dispatch({
        type: USER_LOGIN_REQUEST,
    });

    const config = {
        headers: {
            "Content-Type": "application/json",
        },
    };

    const { data } = await axios.post(
        "/api/auth/login",
        { email, password },
        config
    );

    dispatch({
        type: USER_LOGIN_SUCCESS,
        payload: data,
    });

    localStorage.setItem("user", JSON.stringify(data.token));
} catch (error) {
    dispatch({
        type: USER_LOGIN_FAIL,
        payload:
            error.response && error.response.data.message
                ? error.response.data.message
                : error.message,
    });
}

loginReducer.js

export const userLoginReducer = (state = {}, action) => {
switch (action.type) {
    case USER_LOGIN_REQUEST:
        return { loading: true };
    case USER_LOGIN_SUCCESS:
        return { loading: false, userInfo: action.payload };
    case USER_LOGIN_FAIL:
        return { loading: false, error: action.payload };
    case USER_LOGOUT:
        return {};
    default:
        return state;
}};
R4ve
  • 3
  • 4
  • `dispatch(login(email, password)).then(() => error ? alert(error) : alert("success"));` Where does the `error` variable come from? Please provide a [mvce](https://stackoverflow.com/help/minimal-reproducible-example) – Lin Du Nov 29 '21 at 05:56
  • @slideshowp2 the error comes from the loginActions.js, specifically from the API request, if the email or password is invalid the API sends a status code of 401 and specifies the error – R4ve Nov 29 '21 at 16:13

0 Answers0