Reputation: 1449
I have question regarding on props navigation, I was wondering how can i navigate other screen if condition is true? I have module where the user need to login, I am using ReactJS api. Moving forward, I can get the right response in the api, however there is problem on my if statement that my props is undefined is not an object.
I have here my codes that I made,
AsyncStorage.getItem('authorization_code', (err, result) => {
let token = result;
axios({
method: 'post',
url: 'http://1xx.xx.x.xx:8002/api/auth/me?token=',
headers: {"Authorization" : `Bearer ${token}`}
}).then(response => {
const email = response.data.email;
const user_type = response.data.user_type;
AsyncStorage.setItem('USERMAIL',email.toString());
AsyncStorage.setItem('USERTYPE',user_type.toString());
if(user_type == 1) {
this.props.navigation.push('Dashboard');
}
else if(user_type == 3) {
this.props.navigation.push('Dashboard');
}
})
});
Thanks.
Upvotes: 2
Views: 2277
Reputation: 3777
This is because you're accessing this
in another closure. To fix this, you can store a local variable and access it from within the function passed to then
. A common convention is to make a new variable called that
with the this
you want to persist to the closure.
getItemFromStorage() {
// this line is the key
const that = this;
AsyncStorage.getItem('authorization_code', (err, result) => {
let token = result;
axios({
method: 'post',
url: 'http://1xx.xx.x.xx:8002/api/auth/me?token=',
headers: {"Authorization" : `Bearer ${token}`}
}).then(response => {
const email = response.data.email;
const user_type = response.data.user_type;
AsyncStorage.setItem('USERMAIL',email.toString());
AsyncStorage.setItem('USERTYPE',user_type.toString());
// now you can access that to obtain the props
if(user_type == 1) {
that.props.navigation.push('Dashboard');
}
else if(user_type == 3) {
that.props.navigation.push('Dashboard');
}
})
});
}
Upvotes: 1