Open In App

How to get single cache data in ReactJS ?

Last Updated : 20 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

We can use cache storage using window cache and in React JS to get single cache data. We can get single cache data from the browser and use it in our application whenever needed. Caching is a technique that helps us to store a copy of a given resource in our browser and serve it back when requested.

Prerequisites:

Approach

To get single cache data in React JS define getSingleCacheData function which takes the cache name and gets its data from the browser cache. When we click on the button, the function is triggered and data gets fetched from the cache. In the following example, we are trying to fetch single cache data named CacheOne from the browser which has five caches named CacheOne, CacheTwo, CacheThree, CacheFour, and CacheFive as shown below:

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app foldername

Step 2: After creating your project folder i.e. foldername, move to it using the following command:

cd foldername

Project Structure:

Project Structure

Example: This example use Window cache to access the cache storage and get a specific cache data.

Javascript




//  Filename - App.js
 
import * as React from "react";
 
export default function App() {
    // Our state to store fetched cache data
    const [cacheData, setCacheData] = React.useState();
 
    // Function to get single cache data
    const getSingleCacheData = async (cacheName, url) => {
        if (typeof caches === "undefined") return false;
 
        const cacheStorage = await caches.open(cacheName);
        const cachedResponse = await cacheStorage.match(
            url
        );
 
        // If no cache exists
        if (!cachedResponse || !cachedResponse.ok) {
            setCacheData("Fetched failed!");
        }
 
        return cachedResponse.json().then((item) => {
            setCacheData(item);
        });
    };
 
    // Cache Object
    const cacheToFetch = {
        cacheName: "CacheOne",
        url: "https://localhost:300",
    };
 
    return (
        <div style={{ height: 500, width: "80%" }}>
            <h4>
                How to get single cache data in ReactJS?
            </h4>
            <button
                onClick={() =>
                    getSingleCacheData(
                        cacheToFetch.cacheName,
                        cacheToFetch.url
                    )
                }
            >
                Get Single Cache Data
            </button>
            <br />
            <h6>Cache Data is: {cacheData} </h6>
        </div>
    );
}


Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output: Now open your browser and go to http://localhost:3000/, you will see the following output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads