I want to know if what I've written below is the correct approach to make a request to an API. If not please help and suggest anything that is not correct.
function readQuoteFromRSS(rssUrl) {
fetch(rssUrl).then(function(response) {
return response.json();
}).then(function(response) {
setStore(response);
});
}
CodePudding user response:
It's mostly fine, except that unfortunately it's falling prey to the fetch
API footgun I describe in the link Ivar gave you — fetch
only rejects its promise on network errors, not HTTP errors like 404 or 500. So you have to check for HTTP errors on the response object.
A couple of other things:
It's important to either handle rejection or return the promise chain from the function so the caller can (usually you want to do the latter, but if this is an entry point like an event handler, there's nowhere to pass it to and you have to handle it locally).
I probably wouldn't use
response
for the name of the parameter in the lastthen
, since it won't be a Response object anymore as it was in the previous handler. Perhapsdata
.
function readQuoteFromRSS(rssUrl) {
return fetch(rssUrl) // *** return
.then(function (response) {
if (!response.ok) { // *** check
throw new Error(`HTTP error ${response.status}`); // *** for HTTP
} // *** error
return response.json();
})
.then(function (data) {
setStore(data);
});
}
Purely as a matter of style, since modern environments support async
/await
, I'd probably use it:
async function readQuoteFromRSS(rssUrl) {
const response = await fetch(rssUrl);
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
const data = await response.json();
setStore(data);
}