Cached API call with expiry time
const key = `${URL}${JSON.stringify(config)}` is made like this const key = JSON.stringify(URL) + JSON.stringify(config) in the below code.
function CachedAPICall(delay) {
const cache = {};
return async (URL, config = {}) => {
const key = JSON.stringify(URL) + JSON.stringify(config);
const entry = cache[key];
if (!entry || Date.now() > entry.expiry) {
console.log("Making a fresh API URL call");
try {
const res = await fetch(URL, config);
const data = await res.json();
cache[key] = { value: data, expiry: Date.now() + delay };
} catch (e) {
console.log("Error in the API URL calling");
}
}
return cache[key].value;
};
}
const API = "https://jsonplaceholder.typicode.com/todos/1";
const cachedAPICall = CachedAPICall(1500);
cachedAPICall(API, {}).then((res) => console.log(1, res));
setTimeout(() => {
cachedAPICall(API, {}).then((res) => console.log(2, res));
}, 700);
setTimeout(() => {
cachedAPICall(API, {}).then((res) => console.log(3, res));
}, 2000);
// Making a fresh API URL call
// 1
// {
// userId: 1,
// id: 1,
// title: "delectus aut autem",
// completed: false,
// }
// 2
// {
// userId: 1,
// id: 1,
// title: "delectus aut autem",
// completed: false,
// }
// Making a fresh API URL call
// 3
// {
// userId: 1,
// id: 1,
// title: "delectus aut autem",
// completed: false,
// }