Blog>
Snippets

Handling Dynamic Content Caching

Implement a caching strategy for dynamic content where data is often updated and needs to reflect changes while still benefiting from cache efficiency.
// Function to fetch dynamic content and manage cache
async function fetchDynamicContent(url) {
    const cacheKey = url;
    const cached = sessionStorage.getItem(cacheKey);

    if (cached !== null) {
        // Parse the cached JSON string back into an object
        return JSON.parse(cached);
    }

    try {
        const response = await fetch(url);
        const data = await response.json();

        // Cache data for a limited time to ensure updates are reflected
        sessionStorage.setItem(cacheKey, JSON.stringify(data));
        // Set a timeout to clear the cache after a given time (e.g., 5 minutes)
        setTimeout(() => sessionStorage.removeItem(cacheKey), 5 * 60 * 1000);

        return data;
    } catch (error) {
        console.error('Fetching dynamic content failed:', error);
        throw error;
    }
}

// Example usage of the fetchDynamicContent function
// fetchDynamicContent('https://api.example.com/data').then(console.log).catch(console.error);
This code defines a function to fetch dynamic content from a given URL and utilize session storage for caching. The cache is checked first, and if the data is available and not expired, it is used; otherwise, the content is fetched from the server. The cache is set to auto-expire after a specific time (e.g., 5 minutes) to ensure content freshness.