Skip to content

localStorage

pierr edited this page Nov 16, 2014 · 6 revisions

Vanilla JS (standard js)

The localStorage is

//Save the object in the localStorage.
localStorage.setItem("key", JSON.stringify({firstName: "Pierre", lastName: "Besson"})); 

// return the stringified object.
localStorage.getItem("key")

//In order to have the real object
JSON.parse(localStorage.getItem("key")); //Return {firstName: "Pierre", lastName: "Besson"}

All these operation are synchronous, this means the localStorage. Here is a detail article of mozilla on it.

localforage

** This is how we will proceed in projects.** In order to be more efficient with local storage and also provide a way to use other storage which will be available in HTML5 such as indexedDB we will use a library provided by Mozilla which is localforage.

The syntax is almost the same as for the local storage but each operation is asynchronous.

//Save the object in the local storage
localforage.setItem("key", {firstName: "Pierre", lastName: "Besson"}); 
//Get an object
localforage.getItem("key");

However , these operations are asynchronous, so the function call to getItem or setItem will return a Promise. In order to get the result from the action you are doing you have to execute the Promise with a promise.then(function success(data){console.log(data);}, function failure(err){console.error(err);}). In the focus framework, all your services which are doing a localstorage access, will be able to return directly the Promise

Clone this wiki locally