I am trying to post data to my API using axios. I need to request and send a XSFR-token along with the request. I am using React, Redux, Thunk and Axios. I need to have this handled as a promise inside the React component itself. It is now but it doesn't respond in the desired way. It always resolves the promise, even if the post failed, as long a the token request succeeded.
My call to start this in my React component is at the bottom, it gives me yes even if the axios call failed on the post and I do get the error message from the catch on the second call. If I put a Promise.reject() in there it also gets sent but uncaught because a promise has already been returned, I think.
I tried wrapping the entire thing in a return Promise.all([getToken()...]). It works but behaves exactly the same and still gives me a resolve from the success at receiving the token and disregards the second axios call.
Actions:
export function Post(data) {
return (dispatch) => {
return getToken('csfr')
.then(response => {
return axios.post( '/post', {
request: data,
token: response,
apitoken: 'apikey',
})
.then(response => {
dispatch({type: 'POST', payload: response});
})
.catch(error => {
dispatch(errorPopup({visible: true, message: error}));
throw error;
});
})
.catch(error => {
dispatch(errorPopup({visible: true, message: error}));
});
};
}
export function getToken(tokentype) {
return axios.post( '/token/' + tokentype, {
apitoken: 'apikey',
})
.then()
.catch(error => {
throw error;
});
}
React component (Post action is bound to props using Redux):
componentWillMount() {
this.props.Post(this.state.data)
.then(() => {
console.log('yes')
})
.catch(() => {
console.log('no')
});
}