NinetyHH NinetyHH - 3 months ago 17
React JSX Question

React-Native: Passing an if statement if the object is undefined

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!

Answer

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);
        });
Comments