Thursday, November 28, 2024
Google search engine
HomeLanguagesHow to delete multiple cache data in ReactJS ?

How to delete multiple cache data in ReactJS ?

We can use the following approach in ReactJS to delete multiple cache data in ReactJS. We can delete multiple cache data from the browser as per the user requirement. 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 delete specific cache data in ReactJS. We have created our deleteMultipleCache function which takes the cache names as an array and deletes it from the browser cache. When we click on the button, the function is triggered, and the given caches get deleted from the browser and, and we see an alert popup. 

In the following example, we have 5 caches stored in the browser named CacheOne, CacheTwo, CacheThree, CacheFour, and CacheFive as shown below, and we delete CacheOne and CacheFour using our defined function.

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.

Project Structure

Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.

App.js




import * as React from 'react';
  
export default function App() {
  
  // Function to delete our give caches
  const deleteMultipleCache = (cacheArray) => {
    for (var i = 0; i < cacheArray.length; i++) {
      if ("caches" in window) {
        caches.delete(cacheArray[i]).then(function (res) {
          return res;
        });
      }
    }
    alert('Multiple Caches Deleted!')
  };
  
  return (
    <div style={{ height: 500, width: '80%' }}>
      <h4>How to delete multiple cache data in ReactJS?</h4>
      <button onClick={() => deleteMultipleCache(['CacheOne', 'CacheFour'])} >
        Delete Multiple Cache</button>
    </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:

Whether you’re preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, neveropen Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we’ve already empowered, and we’re here to do the same for you. Don’t miss out – check it out now!

RELATED ARTICLES

Most Popular

Recent Comments