So I'm trying to retrieve repo data from the Github API for a React app. Due to the rate-limiting on the API, I'm attempting to use conditional requests to check if the data has been modified since the last request, using the If-Modified-Since header.
Here is my test code so far:
const date = new Date().toUTCString();
fetch('https://api.github.com/users/joshlucpoll/repos', {
headers: {'If-Modified-Since': date}
})
.then((res) => {
let headers = res.headers;
console.log(headers)
if (headers.get('status') === "304 Not Modified") {
console.log("Not modified")
}
else {
console.log("modified")
}
});
Every time I run this code I get a 200 OK status, not a 304 Not Modified as expected. The resource can't have updated in the time it's taken to run the code, however, it always outputs "Not modified"...
I can't understand why this isn't working, help would be appreciated!
The issue here is the way you are handling the status.
Here is a little setup on how it should be implemented : https://codesandbox.io/s/wizardly-banzai-pi8to?file=/src/index.js
const date = new Date().toUTCString();
fetch("https://api.github.com/users/joshlucpoll/repos", {
headers: { "If-Modified-Since": date }
}).then((res) => {
console.log(res.status);
});
The status can be retrieved inside the response itself, it's not nested inside the headers.
You will see that the value of res.status is 304, res.headers.get("status") will return null
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With