We can use the following approach in ReactJS to get multiple cache data. We can get multiple cache data from the browser and use them in our application whenever needed. Caching is a technique that helps us to stores a copy of a given resource into our browser and serves it back when requested.
Approach: Follow these simple steps in order to get multiple cache data in ReactJS. We have created our getMultipleCacheData 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 multiple cache data named CacheOne and CacheFour 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: It will look like the following.
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import * as React from 'react' ; export default function App() { // Our state to store fetched cache data const [cacheData, setCacheData] = React.useState(); // Function to get multiple cache data const getMultipleCacheData = async (cacheNames) => { if ( typeof caches === 'undefined' ) return false ; var cacheDataArray = [] for ( var i = 0; i < cacheNames.length; i++) { const cacheStorage = await caches.open(cacheNames[i].cacheName); const cachedResponse = await cacheStorage.match(cacheNames[i].url); // If no cache exists if (!cachedResponse || !cachedResponse.ok) { cacheDataArray[i] = `Unable to fetch ${cacheNames[i].cacheName}` } else { var data = await cachedResponse.json() cacheDataArray[i] = data } } // Putting commas in between caches data // to display properly setCacheData(cacheDataArray.join( ', ' )) }; // Caches names which has to be fetched from browser const cachesToFetch = [ ] return ( <div style={{ height: 500, width: '80%' }}> <h4>How to get multiple cache data in ReactJS?</h4> <button onClick={() => getMultipleCacheData(cachesToFetch)} > Get Multiple Cache Data</button> <br /> <h6>Multiple 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: