Storing and retrieving objects with localStorage in HTML5

Reference

For this example we will be using TypeScript and a strongly typed interface.

interface Inputs {
  bodyWeight: string;
  scale: string;
}

localStorage stores key-value pairs. So to store a entire javascript object we need to serialize it first (with JSON.stringify, for example):

Save to local storage

let inputs: Inputs = { bodyWeight: '180', scale: '1'};
localStorage.setItem('MyKey', JSON.stringify(inputs));

Retrieve from local storage

const savedInputs: any = localStorage.getItem('MyKey');
inputs = JSON.parse(savedInputs);

Delete all local storage entries

localalStorage.clear();

You can find JSON library to stringify and parse the objects here: http://json.org/

Leave a Reply

Your email address will not be published. Required fields are marked *