Reputation: 170
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...
Upvotes: 0
Views: 9660
Reputation: 1
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();
});
Upvotes: 0
Reputation: 10273
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
Upvotes: 1
Reputation: 144
Try using a promise !
check out google documentation on promises!
https://developers.google.com/web/fundamentals/getting-started/primers/promises
handleDeleteBlackList(id, event) {
return new Promise(function(accept,reject) {
perform_first_request()
.then(function(){
perform_second_request()
})
})
}
Upvotes: 2