This is a follow up to a previous post, Browser storage: 4 key considerations for implementing browser storage. Check that post for general information on the following topics:

  • Choosing either session or local storage
  • Using an appropriate storage key (preferably vendor prefixed)
  • Storing and retrieving complex data with JSON stringify and parse utility methods
  • Giving data an expiration date

With these points in mind lets see how to implement the 3 basic actions involved with caching data in browser storage: saving, retrieving, and clearing browser storage data.

Saving to local or session storage

Saving is fairly straightforward. The key consideration is to JSON.stringify data before saving in order to support objects. Additionally, we save the date of storage separately with a standardized naming convention.

I consider local storage the more frequent use case so the useSession boolean parameter is optional.

Note: adding the + operator to date object will convert it to number.

function save(key, data, useSession) {
  // json stringify data
  const saveData = JSON.stringify(data);

  // save to local or session storage
  if (useSesson) {
    sessionStorage.setItem(key, saveData);

    // store date
    sessionStorage.setItem(key + '_date', +(new Date());
  } else {
    localStorage.setItem(key, saveData);

    // store date
    localStorage.setItem(key + '_date', +(new Date());
  }
}

Retrieving from local or session storage

Note, if data is retrieved we need to JSON.parse it since we saved a json string.

The expirationMinutes parameter indicates the number of minutes from time of storage before data is considered expired. If data is expired or if I can't find an associated date I like to tidy up by clearing the data from storage.

function retrieve(key, expirationMinutes, useSession) {
  let data, date;

  if (useSession) {
    data = sessionStorage.getItem(key);
    date = sessionStorage.getItem(key + '_date');
  } else {
    data = localStorage.getItem(key);
    date = localStorage.getItem(key + '_date');
  }

  // parse json data
  data = JSON.parse(data);

  // return data if no expiration
  if (!expirationDate || expirationDate <= 0) {
    return date;
  }

  // determine if expired 
  const expired = false; // ... see example later on

  // clear expired data
  if (expired || !date) {
    data = null;
    clear(key, useSession);
  } else {
    return data;
  }
}

Clearing data from local or session storage

Clearing local or session storage utilizes the delete operator. Since we store the date separately, we should clear this as well as the primary data.

function clear(key, useSession) {
  if (useSession) {
    delete sessionStorage[key];
    delete sessionStorage[key + '_date'];
  } else {
    delete localStorage[key];
    delete localStroage[key + '_date'];
  }
}

Blog post series

In the next post we'll learn how to add these functions to a service class: Browser storage: Add caching to a service.


Last updated