So I have a small login to an API and my problem now is that if the login didn't worked, I am displaying an alert message. But when I am passing the good user I'm getting that the error object res.errors[0] is undefined (which of course is true). What is a good way to remake this code to work on both?
Here is my code:
LoginAPI.getToken(this.state.value)
.then((res) => {
if (typeof res.errors[0] !== 'undefined') {
if (res.errors[0].code === 'auth.credentials') {
this.setState({
error: 'Username or Password are incorrect!',
isLoading: false,
token: null
});
Alert.alert(
'Login',
this.state.error
)
}
}
else {
this.setState({ token: res });
LoginAPI.getUser(this.state.token)
.then((res) => {
Actions.dashboard({userData: res});
});
this.setState({
isLoading: false
});
}
}).catch((error) => {
console.error(error);
});
Thank you for your time!
When checking for a nested value in an object or array you should check it like this.
if (res && res.errors && res.errors[0] && res.errors[0].code === 'auth.credentials') {
Most likely it's trying to read a property of an undefined object property, and JavaScript does not like that. So your logic would look something more like this.
LoginAPI.getToken(this.state.value)
.then((res) => {
if (res && res.errors && res.errors[0] && res.errors[0].code === 'auth.credentials') {
this.setState({
error: 'Username or Password are incorrect!',
isLoading: false,
token: null
});
Alert.alert(
'Login',
this.state.error
)
}
else {
this.setState({ token: res });
LoginAPI.getUser(this.state.token)
.then((res) => {
Actions.dashboard({userData: res});
});
this.setState({
isLoading: false
});
}
}).catch((error) => {
console.error(error);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.