JAVASCRIPT
Client-Side API Response Caching with LocalStorage
Implement basic client-side caching for API responses using JavaScript's `localStorage` to reduce redundant requests and improve application performance.
const CACHE_KEY_PREFIX = 'api_cache_';
const CACHE_EXPIRATION_TIME = 5 * 60 * 1000; // 5 minutes in milliseconds
async function fetchWithCache(url, options = {}) {
const cacheKey = CACHE_KEY_PREFIX + url;
const cachedData = localStorage.getItem(cacheKey);
if (cachedData) {
const { timestamp, data } = JSON.parse(cachedData);
if (Date.now() - timestamp < CACHE_EXPIRATION_TIME) {
console.log('Returning cached data for:', url);
return data; // Return cached data if not expired
} else {
console.log('Cached data expired for:', url);
localStorage.removeItem(cacheKey); // Remove expired cache
}
}
console.log('Fetching fresh data for:', url);
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const freshData = await response.json();
// Cache the fresh data with a timestamp
const dataToCache = {
timestamp: Date.now(),
data: freshData
};
localStorage.setItem(cacheKey, JSON.stringify(dataToCache));
return freshData;
} catch (error) {
console.error('Error fetching data with cache:', error);
throw error;
}
}
// Example Usage:
// fetchWithCache('https://api.example.com/products')
// .then(data => console.log('Products:', data))
// .catch(error => console.error('Failed to get products:', error));
// fetchWithCache('https://api.example.com/users/1');
How it works: This JavaScript snippet provides a simple mechanism for client-side API response caching using `localStorage`. It checks if a recent response for a given URL exists in the cache. If found and not expired, it returns the cached data immediately. Otherwise, it makes a fresh API request, stores the new data along with a timestamp in `localStorage`, and then returns it, improving performance and reducing server load.