JAVASCRIPT
Client-Side API Response Caching
Implement a simple client-side cache using `Map` or `localStorage` to store API responses, reducing redundant requests and improving application performance.
const apiCache = new Map(); // In-memory cache
async function fetchWithCache(url, options = {}, cacheDurationMs = 300000) { // Default 5 minutes
const cacheKey = JSON.stringify({ url, options });
const cachedResponse = apiCache.get(cacheKey);
if (cachedResponse && (Date.now() - cachedResponse.timestamp < cacheDurationMs)) {
console.log(`Serving from cache: ${url}`);
return cachedResponse.data;
}
console.log(`Fetching from API: ${url}`);
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
// Store in cache
apiCache.set(cacheKey, {
data: data,
timestamp: Date.now()
});
return data;
} catch (error) {
console.error('Error fetching data with cache:', error);
throw error;
}
}
// Example Usage:
// fetchWithCache('https://jsonplaceholder.typicode.com/posts/1', {}, 60000) // Cache for 1 minute
// .then(data => console.log('Post 1:', data))
// .then(() => fetchWithCache('https://jsonplaceholder.typicode.com/posts/1', {}, 60000)) // Will serve from cache
// .then(data => console.log('Post 1 (cached):', data))
// .catch(error => console.error('Failed to fetch or cache:', error));
// // For more persistent caching across sessions, localStorage can be used
// function fetchWithLocalStorageCache(url, cacheKey, cacheDurationMs = 3600000) {
// const cached = localStorage.getItem(cacheKey);
// if (cached) {
// const { data, timestamp } = JSON.parse(cached);
// if (Date.now() - timestamp < cacheDurationMs) {
// console.log('Serving from localStorage cache:', url);
// return Promise.resolve(data);
// }
// }
// return fetch(url).then(res => res.json()).then(data => {
// localStorage.setItem(cacheKey, JSON.stringify({ data, timestamp: Date.now() }));
// return data;
// });
// }
// fetchWithLocalStorageCache('https://jsonplaceholder.typicode.com/todos/1', 'todos_1')
// .then(data => console.log('Todo 1 (from local storage):', data));
How it works: This snippet demonstrates how to implement a basic client-side cache for API responses using an in-memory `Map`. It checks if a recent response for a given URL and options combination exists in the cache before making a network request. If available and not expired, the cached data is returned, reducing API calls and improving performance. A commented out section shows how `localStorage` could be used for persistent caching across sessions.