Reputation: 79
In my login page, I use axios to send a response to server in a separate function and I use a callback to set the Login component state in the main Login component. The trouble is, I get a Uncaught (in promise) TypeError: Cannot read property 'status' of undefined
. A console.log
in the catch shows me TypeError: onSucceed is not a function
(onSucceed
is the callback function in case of Status 200
). But my console.log
in .then
is also displayed. What the hell? Are my callbacks really wrong?
My Request function:
import axios from "axios";
export const loginRequest = (state, onSucceed, onCatch) => {
axios.post("api/auth", { "email": state.email, "password": state.password })
.then((response) => {
console.log(response);
if (response.status === 200) onSucceed(response);
}).catch(exception => {
console.log(exception);
if (exception.response.status === 400) onCatch();
});
}
Here's my form submit handle:
const handleSubmit = (event) => {
if (state.password === "" || state.email === "") {
event.preventDefault();
setState({
...state,
emptyForm: true
})
return;
}
event.preventDefault();
loginRequest(state, props,
(response) => {
props.loggingIn(response.data.userName, response.data.name);
setCookie({
userName: response.data.userName,
fullName: response.data.name, expireDays: 0.125, isLoggedIn: true
});
history.push("/");
},
() => {
setState({ ...state, badCredentials: true });
});
Upvotes: 0
Views: 577
Reputation: 498
The onSuccess
function is missing before you call it, as the error points out, and that's why your then
block throws an error, which passes the execution to the catch
block (in which the log shows exactly that this is the error). As for TypeError: Cannot read property 'status' of undefined
, this is probably encountered in the catch
block, where you try to test the condition for exception.response.status === 400
, exception.response
might be undefined, so trying to access status
of undefined would cause the application to crush.
Also noticed that on your submit handler function, you call loginRequest
with the wrong arguments. There's 4 arguments provided instead of 3 that are expected (state, onSuccess, onCatch). Try to remove props
from the arguments you pass to the function.
Upvotes: 2