caches.delete is not deleting anything

1.1k views Asked by At

Im trying to write a function that will accept a string and remove from cache memory the correct item. My function is:

export const removeItemFromCache = async (name: string | null) => {
  console.log('got here with name:', name)
  if (!name) return;
  await caches.delete(name);
};

In the console, I see got here with name: files/4325 and I clearly have an item with the same name.

The way I use this function is:

  await removeItemFromCache(file.name);

but the file remains in the cache memory even after I refresh the cache or even reload the page. Am I missing something / doing something wrong?

I used this https://developer.mozilla.org/en-US/docs/Web/API/CacheStorage/delete as a reference.

2

There are 2 answers

0
YTG On BEST ANSWER

This function worked for me:

  export const removeItemFromCache = async (name: string) => {
  for (const entry of await caches.keys()) {
    window.caches.open(entry).then(async cache => {
      return await cache.delete(name);
    });
  }
};
1
John Mullaney On

I have found something that works. BTW: This code runs outside of the service worker.

async function delete_cache_by_name(cacheName_to_delete)
{
    caches.open(cacheName_to_delete).then((cache) => {
        console.log(`delete_cache_by_name: cache.add: ${cache.add}`);
    }).catch((err) => {
        console.log(`delete_cache_by_name: error on open: ${err}`);
    });
    caches.delete(cacheName_to_delete).then((bool_result) => {
        console.log(`delete_cache_by_name: bool_result from delete: ${bool_result}`);
    });
    caches.has(cacheName_to_delete).then((bool_result) => {
        console.log(`delete_cache_by_name: has cache "${cacheName_to_delete}"? ${bool_result}`);
    }).catch((err) => {
        console.log(`delete_cache_by_name: error on has: ${err}`);
    });
}

// THESE ATTEMPTS FAILED EVEN THOUGH THE CODE SEEMED TO WORK

//     window.caches.keys().then(function(cacheNames) {
//         cacheNames.forEach(function(cacheName) {
//             if (cacheName === cacheName_to_delete)
//             {
//                 caches.delete(cacheName);
// alert(`delete_cache_by_name: deleted cache: ${cacheName}`);
//             }
//         });
//     });


// const result = await caches.delete(cacheName_to_delete);
// if (result)            // if successfully deleted the specified cache
//     alert(`delete_cache_by_name: successfully deleted cache: ${cacheName_to_delete}`);
// else
//     alert(`delete_cache_by_name: ERROR could not delete cache: ${cacheName_to_delete}`);