Reputation: 489
I am usually an angular developer and am working in react. Please excuse if this question seems simple.
I have a simple PROMISE
return axios(`team/${this.state.teamId}/player`, this.state)
.then((response) => {
console.log('formSubmit success');
this.store.dispatch({
type: constants.PLAYER_UPDATE,
payload: response.data.user,
});
return false;
})
.catch((error) => {
console.error('Error', error.response.data);
this.setState({
saveStatus: error.response.data.message
});
return Promise.reject(error)
});
In the network tab I can see that URL fetched fine.
Also store.dispatch
is called as it is printed in console.
But at same time it is calling code in the catch statement. My console output is
formSubmit success Player.js:127
Store BEFORE | PLAYER_UPDATE Store.js:76
Uncaught (in promise) TypeError: Cannot read property 'data' of undefined
at Player.js:135
Why is it going after CATCH() when everything is success? I even added return statement at the end of this.store.dispatch
Please help.
Upvotes: 2
Views: 783
Reputation: 5270
The catch
function will catch any error which will come in the then
, if you want to just catch the error in promise, you probably want to use the second callback in then
function. You should do something like this:
return axios.get(`endpoint`)
.then(successCallback, errorCallback);
OR, in your case,
return axios(`team/${this.state.teamId}/player`, this.state)
.then((response) => {
console.log('formSubmit success');
this.store.dispatch({
type: constants.PLAYER_UPDATE,
payload: response.data.user,
});
return false;
}, (error) => {
console.error('Error', error.response.data);
this.setState({
saveStatus: error.response.data.message
});
return Promise.reject(error)
});
Upvotes: 2