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

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube