Reputation: 1054
I want to override the fetch()
method of isomorphic-fetch such that, just before sending this request it calls showLoader()
and after the request is finished, it calls hideLoader()
. Now I want to override it such that the new fetch can be chained just like the original fetch method. So it should respect/forward all the Promises. In summary, I want to:
fetch()
into fetchPlus(extraArg)
fetchPlus()
needs to do addtional work just before calling fetch()
and just after fetch()
completes.fetchPlus()
should be a drop in replacement for usages of original fetch()
fetchPlus(extraArg, originalArgs...).then(response => {...}).catch(error => {...});
I'm fairly new to JS, React and Redux so please excuse me if I missed something obvious. I did read up on fetch()
and know that it returns Promise so that the response can be passed on further or errors be handled. I sort of figured out an ugly way of doing it where, I pass on the responseHandler and errorHandler functions as args to fetchPlus.
fetchPlus(extraArg, url, options, responseHandler, errorHandler) {
showLoader(extraArg);
fetch(url, options)
.then(response => {
hideLoader(extraArg);
responseHandler(response);
}.catch(error => { errorHandler(error); });
}
But I don't find it clean. I want to see if I can find a drop-in replacement for the original fetch where Promises are correctly passed along.
I would highly appreciate any help!
Upvotes: 5
Views: 9722
Reputation: 20614
If you know that it returns a Promise, then why not just return?
fetchPlus(extraArg, url, options) {
showLoader(extraArg);
return fetch(url, options)
.then(response => {
hideLoader(extraArg);
return response;
})
}
Then use it:
fetchPlus(extraArg, url, options)
.then(response => ...)
.catch(error => ...)
Upvotes: 7