Skip to content

resetCacher()

Amphiluke edited this page Nov 30, 2025 · 2 revisions

Synopsis

For cases where manual cache invalidation is required, the library provides a function resetCacher() specifically designed for this purpose. You can use it to clear internal cache storage of your cacher either selectively (on the key basis) or in its entirety.

Simple cacher reset

The first and the only required parameter of the reset function is a cacher you’ve created using the createCacher() API.

import {createCacher, resetCacher} from 'async-aid';

const getCountries = createCacher(async () => {
  const response = await fetch('/geo-api/countries');
  return await response.json();
});

let countries = await getCountries();

window.addEventListener('languagechange', async () => {
  // User’s preferred languages changed!
  // Re-fetching the list of countries with appropriate localisation…
  resetCacher(getCountries);
  countries = await getCountries();
});

Key-based cacher reset

If your cacher maintains multiple caches, you may also provide a distinct cache key as a second argument to clear cache for this specific key only. Not providing a key results in clearing the entire storage of your cacher.

import {createCacher, resetCacher} from 'async-aid';

const getCountriesByContinent = createCacher(async (continentCode) => {
  const response = await fetch(`/geo-api/countries?continent=${continentCode}`);
  return await response.json();
}, {
  keyFn: (continentCode) => continentCode,
});

let hemisphere = 'unknown';

navigator.geolocation.watchPosition(({coords}) => {
  const newHemisphere = coords.longitude < 0 ? 'western' : 'eastern';
  if (newHemisphere === hemisphere) {
    return;
  }
  hemisphere = newHemisphere;
  // The user has crossed the hemisphere boundary! Get rid of irrelevant caches
  const resetCodes = hemisphere === 'western' ? ['AF', 'AS', 'EU'] : ['NA', 'SA'];
  resetCodes.forEach((code) => resetCacher(getCountriesByContinent, code));
});

Clone this wiki locally