I have a React-Native code that retrieves a data of REST API from backEndless.
In some cases, the data is an empty array. My code return this error:
error [TypeError: undefined is not an object (evaluating 'res.data[0]['ownerId']')]
It means the the AXIOS ENTER the .then part in stead of entering .catch part, it accepts the empty array as a result.
What should I get is Request Failed with code 401, but I can't catch the error.
any help?
here is my code:
export const confirmCode = (phone,code)=>{
return (dispatch,getState)=>{
dispatch(confirmCodeStart());
phone = phone.substring(2);
console.log(''+code+':'+phone+'');
axios.get('/data/Auth?where=code='+code+'&phone='+phone+'')
.then((res) =>{
console.log(res.status);
console.log('entereeeeed');
ownerid = res.data[0]['ownerId'];
//console.log(res.data[0]['ownerId']+"aaaaa");
//getUser(res.data[0]['ownerId'],phone,props);
////////
//api request
axios.post('/users/login',{'objectId':ownerid})
.then(res2=>{
dispatch(confirmCodeSuccess());
//console.log(res.data);
userToken=res2.data['user-token'];
userData=res2.data;
console.log(res2.data);
//const {token,user} = res2.data;????????
axios.defaults.headers.Authorization ='Bearer '+userToken;
//dispatcher.dispatch({type:'SET_TOKEN',payload:{token:userToken}});
//dispatcher.dispatch({type:'SET_USER',payload:{user:userData}});
dispatch(setToken(userToken));
dispatch(setUser(userData));
AsyncStorage.setItem(TOKEN_KEY,userToken);
AsyncStorage.setItem(USER_KEY,JSON.stringify(userData));
})
})
.catch(error=>{
Reactotron.log('error',error);
console.log('error',error);
dispatch(confirmCodeFailure());
})
};
};
You should throw to move compiler to catch part
when you throw inside the then section compiler goes to the nearest catch section
I make following example to my friend to understand promise work flow
Result: