Introduction to HTML LocalStorage API

Spread the love

Web apps can store data locally within the user’s browser instead of storing data in cookies.  LocalStorage is per origin so all pages from an origin can store and access the same data.

The LocalStorage API is used to store key value pairs of data, It also only stores strings, so all data must be converted to strings.

Methods

The methods of the LocalStorage API are:

setItem

The setItem method is used to store a key and its associated value into local storage, if any existing data with the same key exists, it gets overridden with the new value.

syntax

localStorage.setItem(key, value);

getItem

The getItem method is used to retrieve the value associated with a key from local storage, if there is no value associated with the provided key, it returns null.

syntax

localStorage.getItem(key); // returns value associated with key.

removeItem

The removeItem method is used to remove the value associated with a key stored in local storage.

syntax

localStorage.removeItem(key); // removes value associated with key.

clear

The clear method is used to remove all data stored in local storage

syntax

localStorage.clear(); // all data in localstorage is removed, localstorage is now empty.

Common Pitfalls

getItem Always returns value as a string

All data stored in localstorage is stored as strings, data of other types are implicitly converted to strings before being stored.

So if you store a boolean or an int or anything other than a string, you will get back a string when you get it

Example:

var a = true; //a is a boolean
var b = 10; //b is an int
var c; //c is undefined

localStorage.setItem('a',a);
localStorage.setItem('b',b);
localStorage.setItem('c',c);


localStorage.getItem('a'); //returns string 'true'
localStorage.getItem('b'); //returns string '10'
localStorage.getItem('c'); //returns string 'undefined'

Storing Objects

Since localStorage only works with strings, you have to stringify  and parse objects to use them with localStorage

Example:

var obj = {"favorite-color":blue}
localStorage.setItem(obj, JSON.stringify(obj));
obj = JSON.parse(localStorage.getItem(obj));

Browser Quirks

localStorage is supported in almost all browsers, you can find the full list here. But some browsers have some quirks like some versions of iOS store localStorage data in a location that may occasionally be cleared out by the OS.

 
IE11 does not properly synchronize localStorage between different windows

Browsers also set limits (usually 10 Mb) on how much data you can store in localStorage.