I wrote a redux thunk so that after making a post request to an API an action gets dispatched and a callback gets executed:
import actionTypes from '../actions/actionTypes';
import axios from 'axios';
function postThunk(someValue, callback) {
return dispatch => {
try {
let token = localStorage.getItem('token');
const credentials = {
headers: {
"Authorization" : 'Bearer '+ token,
},
};
const data = {
someValue
}
axios.post('http://myAPI',data, credentials).then(result =>{
dispatch({
type: actionTypes.MY_ACTION,
data: result,
})
});
callback();
} catch (error) {
console.log(error);
}
}
}
export{
postThunk
};
The callback when i invoke the thunk is actually then just a this.props.history.push(/somelocation)
.
So as written above it works, but I actually want the callback be inside the axios.post promise chain, because the redicrect should only happen after the POST request. Hoewever if I change the code to this:
axios.post('http://myAPI',data, credentials).then(result =>{
dispatch({
type: actionTypes.MY_ACTION,
data: result,
});
callback();
});
Somehow it doesn´t work anymore. The POST request is happening and the DB gets updated but instead of redirecting the same page gets a hard reload, which makes it also very difficult to debug because i dont really see what´s happening. Does anyone has an idea what i need to look after, is it the dispatch throwing an error or do i need a redux promise middleware at this point??