Using localStorage to persistently store data on client side

Monday, Aug 3, 2020

One option to store data persistently on the client side is localStorage object. Persistent here means that the data will be available even when the browser is closed and reopened. The format is like regular object with one exception - both keys and values must be strings. This requirement can be easily met however using JSON format. While different pages of the same site or the same page opened in multiple tabs can access the same localStorage object, each site maintains its own localStorage and thus data cannot be shared among different sites.

Convert to JSON to store data

let players = [{name: "Carrie", hasPlayed: true}, {name: "Ibrahim", hasaPlayed: false}];
if (!localStorage.players) {
  localStorage.players = JSON.stringify(players);

Parse JSON to use localStorage data

let previousPlayers = JSON.parse(localStorage.players);