How to get complete cache data in ReactJS ?
In react, we can get all 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 all cache data in React JS define getAllCacheData function which gets all 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 all cache data from the browser which has five caches named CacheOne, CacheTwo, CacheThree, CacheFour, and CacheFive as shown below:
Steps to create 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: Get all cache data from the browser cache storage and display on the page when get cache button is clicked
Javascript
import * as React from "react" ;
export default function App() {
const [cacheData, setCacheData] = React.useState();
const getAllCacheData = async () => {
let names = await caches.keys();
let cacheDataArray = [];
names.forEach(async (name) => {
const cacheStorage = await caches.open(name);
const cachedResponse = await cacheStorage.match(
url
);
let data = await cachedResponse.json();
cacheDataArray.push(data);
setCacheData(cacheDataArray.join( ", " ));
});
};
return (
<div style={{ height: 500, width: "80%" }}>
<h4>How to get all cache data in ReactJS?</h4>
<button onClick={() => getAllCacheData()}>
Get All Cache Data
</button>
<br />
<h6>All 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:
Last Updated :
03 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...