Papa's Perspective

A Unified Approach to Client-Side Storage

This simple API can give you a leg up on local storage in your Web apps.

Web apps, generally, have sets of data that either don't change a whole lot, or that represent state -- the configuration, content and attributes -- which must be maintained between page calls. HTTP offers a variety of great features, but state has to be reset between page calls because it's stateless. So where do you store that data in Web applications? The concept of local storage addresses this challenge quite nicely.

Why Use Storage?
Local storage in HTML5 refers specifically to the localStorage object. I recommend using it if you're building an app for an HTML5-compliant browser that implements localStorage. (You can check the popular site, caniuse.com, to see if your browsers support localStorage and other features.) Historically, browsers have used a variety of techniques to store local data, including localStorage, sessionStorage (which differs from localStorage in that its data goes away when the browser closes), globalStorage, cookies and userData.

You can use cookies, but there are some limitations, which Christian Heilmann explains in his article, "Local Storage and How to Use It on Web Sites". It's worth noting that while you can store a lot of data in local storage, you should use this feature judiciously -- it's not a database, after all. Local storage is ideal for retaining data that either doesn't change often (you can set expiration dates), or to help maintain state across pages, tabs and browser sessions.

Say you're building a Web app that supports multiple versions of different browsers. You want to use localStorage where available, but also fall back and provide graceful degradation in older browsers. What do you do? Certainly not a lot of conditional logic -- bleh!

Unified API with Amplify.store
This is the sweet spot for AmplifyJS, a library of jQuery components built by the folks at appendTo LLC. It includes three main features: AJAX requests, pub/sub messaging and storage. The amplify.store object provides a unified way to persist data from a variety of Web browsers. It offers a single API across multiple browsers, which implement storage quite differently. The amplify.store library hides the complexity and logic, so you can focus on storing and retrieving data -- and not on how to handle it in different browsers. You can find a complete list of the amplify.store default storage mechanisms based on browser support here.

Note: If your browser doesn't support JSON2, you must include JSON2.js as well. This is required in Internet Explorer 7 and earlier versions to use the JSON.stringify and JSON.parse methods.

Local storage stores a key value pair, where the key and the value are both strings. What this means is that if you want to store arrays and objects, you should serialize them first, using JSON.stringify (and de-serialize them with JSON.parse). However, if you use amplify.store, it will serialize and de-serialize the data to and from JSON for you.

The following sample code defines an array of people objects:
var testKey = 'people'; 
var testVal = [
  { name: 'John', age: 34, pets: [{name: 'Fido', type: 'dog'},
    {name: 'Tink', type: 'cat'}]},
  { name: 'Landon', age: 14, pets: [{name: 'Iron Man', type: 'dog'}, 
    {name: 'McQueen', type: 'dog'}]}];

You can store these objects using amplify.store by passing a key value, followed by the textVal object. Amplify.store will serialize the data in testVal, do a check for localStorage support (and fallback, if necessary), then store the data.The data can be retrieved using the same store method, by only passing a key value. You can also clear the storage by passing a null in for the value.

Examining Local Storage
You can examine what's currently in local storage by calling amplify.store and passing no parameters. If you want to know which key values are being stored, you could also run a script. You can clear a data value from local storage immediately by calling amplify.store(key, null) or setting an expiration on the data when you store it. Simply pass an optional parameter to the store method following the data value. The parameter is an object containing an expiration value in milliseconds.

The simplicity of the API, its support for the localStorage object and its graceful degradation make this one of my favorite APIs for this space. All of the sample code can be found in this fiddle, which uses toastr to display the values and log the storage and retrieval.

About the Author

John Papa is a Microsoft Regional Director and former Microsoft technical evangelist. Author of 100-plus articles and 10 books, he specializes in professional application development with Windows, HTML5, JavaScript, CSS, Silverlight, Windows Presentation Foundation, C#, .NET and SQL Server. Check out his online training with Pluralsight; find him at johnpapa.net and on Twitter at twitter.com/john_papa.

comments powered by Disqus

Featured

  • Hands On: New VS Code Insiders Build Creates Web Page from Image in Seconds

    New Vision support with GitHub Copilot in the latest Visual Studio Code Insiders build takes a user-supplied mockup image and creates a web page from it in seconds, handling all the HTML and CSS.

  • Naive Bayes Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the naive Bayes regression technique, where the goal is to predict a single numeric value. Compared to other machine learning regression techniques, naive Bayes regression is usually less accurate, but is simple, easy to implement and customize, works on both large and small datasets, is highly interpretable, and doesn't require tuning any hyperparameters.

  • VS Code Copilot Previews New GPT-4o AI Code Completion Model

    The 4o upgrade includes additional training on more than 275,000 high-quality public repositories in over 30 popular programming languages, said Microsoft-owned GitHub, which created the original "AI pair programmer" years ago.

  • Microsoft's Rust Embrace Continues with Azure SDK Beta

    "Rust's strong type system and ownership model help prevent common programming errors such as null pointer dereferencing and buffer overflows, leading to more secure and stable code."

  • Xcode IDE from Microsoft Archrival Apple Gets Copilot AI

    Just after expanding the reach of its Copilot AI coding assistant to the open-source Eclipse IDE, Microsoft showcased how it's going even further, providing details about a preview version for the Xcode IDE from archrival Apple.

Subscribe on YouTube

Upcoming Training Events