So I am building a MERN stack application that does have a login functionality. Whenever the user sends the wrong credentials, I am throwing an error through res.json({errorMessage: 'sample'})
. However, I also implemented Redux in my application and I have an action that looks like this.
export const loginUser =
({ email, password }) =>
async (dispatch) => {
try {
const { data } = await axios.post("http://localhost:5000/auth/login", {
email,
password,
});
dispatch({ type: "LOGIN_USER", payload: data });
} catch (error) {
console.log("Err", error.response.data.errorMessage);
}
};
I am getting the errorMessage here in the actions but I want to display it in React. I am trying to access it in this way but it doesn't work.
const handleSubmit = (e) => {
e.preventDefault();
try {
dispatch(loginUser({ email, password }));
} catch (error) {
console.log(error.response.data.errorMessage);
}
};
I am getting the error in the action and not in my frontend. How can I get the errorMessage in my frontend? Thanks in advance.
You should add throw error in the catch of loginUser
export const loginUser =
({ email, password }) =>
async (dispatch) => {
try {
const { data } = await axios.post("http://localhost:5000/auth/login", {
email,
password,
});
dispatch({ type: "LOGIN_USER", payload: data });
} catch (error) {
console.log("Err", error.response.data.errorMessage);
throw error
}
};
And change handleSubmit
to async
const handleSubmit = async (e) => {
e.preventDefault();
try {
await dispatch(loginUser({ email, password }));
} catch (error) {
console.log(error.response.data.errorMessage);
}
};