I have a signup form in my app that submits data to the my backend server, with a Redux thunk that calls my API and handles the returned data. Right now it only actually catches errors that occur within React/Redux. If the server returns an error, my action creator thinks the error is part of a user record and authenticates my "user", even if I submitted an empty form.
My handleSubmit
function (extracted from my AuthForm component):
const handleSubmit = e => {
e.preventDefault();
onAuth(formType, state);
setState(formType === 'login' ? initialStateLogin : initialStateSignup);
history.push("/");
}
My onAuth function (which maps to my authUser Redux thunk):
export function authUser(type, userData) {
return dispatch => {
return apiCall("post", `/users/${type}`, userData)
.then(({ jwt, ...user }) => {
console.log(jwt, user)
localStorage.setItem("jwtToken", jwt);
setAuthorizationToken(jwt);
dispatch(setCurrentUser(user));
dispatch(removeError());
})
.catch(err => {
console.log(err);
dispatch(addError(err.message));
});
};
}
My apiCall helper function:
export async function apiCall(method, path, data) {
try {
const res = await axios[method.toLowerCase()](`${API_PATH}${path}`, data);
return res.data;
}
catch(err) {
console.log(err);
return err.response.data || "An unknown error occurred";
}
}
If I submit an empty form, my Redux state looks like this:
currentUser {
isAuthenticated: true,
user: {
error: {
message: "Could not create user. Please modify parameters and try again."
}
}
}
You are catching the API calls' erros. This causes your catch callback to never fire. Remove the try/catch block in apiCall
.
Alternatively, you can return a Promise.reject()
with the error data.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments