Storing Arrays in LocalStorage

December 6, 2013 at 4:48 pm in HTML5, Javascript, Web Storage

LocalStorage is amazing. We can persist data right on the client’s computer in the browser. We’ll have 5 to 10 MB of storage available.  However, it’s often not quite good enough for our needs; the values we store must be strings.

But with the help of JSON.stringify() and JSON.parse(), we can use LocalStorage for much more.

var names = [];
// collect some stuff into  the names array.
for(var count=0; count < 5; count++){
  names.push(prompt("New member name?"));
}

// convert the array of names into a JSON string. 
localStorage["names"] = JSON.stringify(names);

Later, we’ll want to retrieve those from the localStorage database. So we turn the string back into an array like this:

var namesFromLocalStorage = JSON.parse(localStorage["names"]);

You could use LocalStorage as a cache for all sorts of things. Simple arrays, complex objects, and even content. Prefetch records from the backend in the background, push it into LocalStorage as a simple cache. When the user hits the “next page” button, display the results of LocalStorage’s content while fetching the next set of records.

How are you using LocalStorage in your projects?

No comments