JAVASCRIPT
Implement Basic Client-Side Caching for API Responses
Improve web application performance and reduce API calls by implementing a simple in-memory client-side cache for frequently accessed API data.
const apiCache = new Map(); // Stores { url: { timestamp, data } }
async function fetchWithCache(url, options = {}, ttl = 300000) { // ttl in milliseconds (5 minutes default)
const cachedEntry = apiCache.get(url);
const now = Date.now();
if (cachedEntry && (now - cachedEntry.timestamp < ttl)) {
console.log(`Fetching ${url} from cache.`);
return cachedEntry.data;
}
console.log(`Fetching ${url} from API.`);
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`API error: ${response.status} ${response.statusText}`);
}
const data = await response.json();
apiCache.set(url, { timestamp: now, data });
return data;
} catch (error) {
console.error(`Failed to fetch or cache ${url}:`, error);
throw error;
}
}
// Usage example:
// async function loadData() {
// try {
// const userData = await fetchWithCache('https://api.example.com/users/1', { method: 'GET' }, 60000); // Cache for 1 minute
// console.log('User data:', userData);
// // Subsequent call within 1 minute will return cached data
// const anotherUserData = await fetchWithCache('https://api.example.com/users/1', { method: 'GET' }, 60000);
// console.log('Another user data (from cache):', anotherUserData);
// // After 1 minute, it will fetch again
// // await new Promise(resolve => setTimeout(resolve, 61000));
// // const refreshedUserData = await fetchWithCache('https://api.example.com/users/1', { method: 'GET' }, 60000);
// // console.log('Refreshed user data:', refreshedUserData);
// } catch (error) {
// console.error('Error loading data:', error);
// }
// }
// loadData();
How it works: This snippet implements a basic in-memory client-side cache for API responses using a `Map`. The `fetchWithCache` function first checks if a response for the given URL exists in the `apiCache` and if it's still fresh (within its Time-To-Live, `ttl`). If valid cached data is found, it's returned immediately, reducing redundant API calls. Otherwise, it makes a new `fetch` request, stores the fresh data along with a timestamp in the cache, and then returns it. This approach significantly improves performance for frequently accessed but slowly changing data.