JavaScript의 Cache API - 단 20줄의 코드만 있으면 됩니다.
5294 단어 tutorialcachejavascriptwebdev
let cache = {};
async function getData(url){
let result = "";
if(cache[url] !== undefined) return cache[url].value;
await fetch(url)
.then(response => response.json())
.then(json => cache[url] = {time: new Date(), value: json});
return cache[url].value;
}
// Interval to clear cache;
setInterval(function (){
if(Object.keys(cache).length > 0){
let currentTime = new Date();
Object.keys(cache).forEach(key => {
let seconds = currentTime - cache[key].time;
if(seconds > 10000){
delete cache[key];
console.log(`${key}'s cache deleted`)
}
})
}
}, 3000);
이제 API를 이렇게 호출할 수 있습니다.
getData("https://jsonplaceholder.typicode.com/todos/1")
.then(data => console.log(data));
If there is a cache value of the current api call then it will return values from cache otherwise call the api and return data while adding the response to cache.
시사

나는 이것이 RTK Query와 React Query 😅보다 훨씬 낫다고 가정하고 있습니다.
Reference
이 문제에 관하여(JavaScript의 Cache API - 단 20줄의 코드만 있으면 됩니다.), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/rajeshroyal/cache-api-in-javascript-with-just-20-lines-of-code-49kg텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념
(Collection and Share based on the CC Protocol.)