I have the following code:
handleDeleteBlackList(id, event) {
this.props.actions.deleteBlackListItem(id, this.props.token);
this.props.actions.fetchBlackListItems(this.props.token);
}
The first line deletes a record from some web service, the second fetches the updated data. Sometimes the system does not wait for the first request to finish before performing the second request and my "updated" data is not updated at all...
I'm looking for some solution to wait for the first request to finish and then perform the second request.
Edit:
I'm already using an workaround with setTimeout function, but it should have a better way of fixing it...
I have the following code:
handleDeleteBlackList(id, event) {
this.props.actions.deleteBlackListItem(id, this.props.token);
this.props.actions.fetchBlackListItems(this.props.token);
}
The first line deletes a record from some web service, the second fetches the updated data. Sometimes the system does not wait for the first request to finish before performing the second request and my "updated" data is not updated at all...
I'm looking for some solution to wait for the first request to finish and then perform the second request.
Edit:
I'm already using an workaround with setTimeout function, but it should have a better way of fixing it...
Share Improve this question edited Feb 17, 2017 at 0:19 Pineda 7,5933 gold badges33 silver badges47 bronze badges asked Feb 16, 2017 at 23:58 DennisDennis 1702 silver badges12 bronze badges 2- This might be of help: github./reactjs/redux/issues/1676 – bejado Commented Feb 17, 2017 at 0:15
- Where is your axios code? If you are using axios, then you'd be able to take advantage of the fact that it uses Promises to handle asynchronous events like this – Pineda Commented Feb 17, 2017 at 0:23
3 Answers
Reset to default 2Try using a promise !
check out google documentation on promises!
https://developers.google./web/fundamentals/getting-started/primers/promises
handleDeleteBlackList(id, event) {
return new Promise(function(accept,reject) {
perform_first_request()
.then(function(){
perform_second_request()
})
})
}
Perhaps using async/await.
async handleDeleteBlackList(id, event) {
const actionResponse = await this.props.actions.deleteBlackListItem(id, this.props.token);
// No idea what you have set your type: to in your action so I just made this up
if (actionResponse && actionResponse.type === 'DELETE_SUCCESS'){
this.props.actions.fetchBlackListItems(this.props.token);
}
}
It would depend how you have structured your actions. Would need to see the code for deleteBlackListItem
There is a method called finally() in Axios, which runs after the call finishes. Like other methods; then() and catch(), finally() method is called after a response is received. But remember that this method get called no matter what your request result is (success or failed). Try writing your second request inside finally() method like
.finally(() => {
your_second_request();
});