Use Mozilla’s LocalForage For Key-Value Storage In Ionic 2

When it comes to saving data in an Ionic 2 mobile application, there are many ways to get the job done.  You can use the classic HTML5 local storage, but run the risk of compatibility problems between all available devices.  You can use SQLite, which is part of Ionic Native, but that will only work for Android and iOS and has more of a mobile API.  You can also use SqlStorage, but that is a very proprietary solution.  This brings us to localForage from Mozilla.

Mozilla advertises localForage as a wrapper to IndexedDB, WebSQL and localStorage which will offer maximum compatibility across the grid.

We’re going to see how to include localForage in our application which is a valid option for Ionic 2.

I actually first heard of localForage from Nolan Lawson who was a guest on my podcast, PouchDB and its Usefulness in Development.  He described it as a better solution to PouchDB if you have no plans to offer synchronization support in your application.

Creating a New Ionic 2 Android and iOS Project

To keep this easy to understand we’re going to create a new Ionic 2 project and include localForage in it.  Using a Command Prompt (Windows) or Terminal (Mac and Linux), execute the following:

There are a few things to note in the above commands.  The --v2 tag means we are creating an Ionic 2 project with TypeScript.  This means you need to have the Ionic 2 CLI.  Also note that I am adding the iOS platform.  If you’re not using a Mac, you cannot build for the iOS platform.

Installing localForage and the TypeScript Type Definitions

The next thing we need to do is install localForage and the TypeScript type definitions that go with it.  Using the Terminal or Command Prompt, execute the following:

Above will install the JavaScript library.  JavaScript libraries don’t play nice in a TypeScript application.  To install the type definitions we’ll need a package called Typings.  Execute the following to install Typings and the necessary type definitions:

Now we can focus on the code.

Using localForage with in the Application with Angular 2

This is going to be a very simple project.  We’ll be able to load the data from localForage and add data to localForage.  This data will be presented on the screen as a list.

Ionic 2 localForage Demo

We’re going to start with the TypeScript logic before we touch the UI.  Open the project’s app/pages/home/home.ts file and include the following code:

There is a lot going on in the above code.  We should break it down to make it easier to understand.

We start things off by importing some very basic Ionic 2 components.  However, we are also importing localForage like so:

This import is how it is said to be done in the official localForage documentation.

Inside the HomePage class we have a public array people which will be bound to the UI.  It will hold all of the saved data.  In the constructor method we do a bit of initialization:

Using localForage is asynchronous and you can use callbacks or promises.  I’ve chosen to use a promise.  If the result of the promise is null, it means the key did not exist, which explains the ternary operation.

Now there is a lot happening in the save method, but it is really just the bootstrap code for an Ionic 2 alert.  What we care about is the following:

We make sure the first name and last name were entered.  If they were, add them to the public array and then save that public array in localForage.

The beauty of localForage is that you can store any data type without having to worry about parsing it out.  This is a benefit in addition to the compatibility that it offers.

Now we can take a look at the HTML UI for this application.  Open the project’s app/pages/home/home.html file and include the following markup:

We essentially have a header with a button in it and a list that shows our public array.  The UI in this application is very basic.

Conclusion

There are many options for saving data when it comes to Ionic 2 mobile applications.  The localForage offering by Mozilla is a very easy to use key-value option that has very good compatibility.  You can store any data type without having to worry about parsing or serializing the data like you would with HTML5 local storage or similar.

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.

  • Alexey Karpov

    Nick, hello! I stumbled across your website researching Ionic2. I’m a web developer looking to building hybrid applications using the Ionic2 framework and the way you document your knowledge and experimentation is a lot of help :). I’m glad I signed up for the premium membership, looking forward to more Ionic2 examples and blog posts!

    In regard to using Mozilla localforage with Ionic2 for local storage, I was wondering if you can comment on the feasability of using the JS Library Forge (saw it mentioned in an earlier article) for encryption of such locally stored data?

  • Ricardo

    Hello Nick, Awesome post very usefull. I am currently looking for the best way to handle adding data syncing, and local caching to a ionic2 app. We have a PostgresSql backend so my solution was to add some method of data synching, and also maintain a local sql db. I looked into PouchDB, but I am unsure if how to fit that into our current project since we have an existing api interface with the server. Any advice would be appreciated.

    • Typically you wouldn’t want to use an RDBMS for a sync project. That is where NoSQL thrives. PouchDB + Couchbase, Firebase, etc.

      Too many edge cases to worry about when you try to make your own sync solution with an RDBMS.

      Best,

  • Todd Greenwald

    Nick,

    Ionic2 complaining “Cannot find module ‘localforage’

    Have tried your:
    declare var require: any;
    const localforage: LocalForage = require(“localforage”);

    as well as what seems the updated recommendation:
    import * as localforage from “localforage”;

    no luck,

    Using the latest versions of Ionic and angular2…

    T

    • RC0 is having some major issues. I think there were some changes, but I’m not going to dare make any updates until things with the latest Ionic release settle down. Stay tuned.

      • Todd Greenwald

        Makes sense.

        T

  • Phil

    Nick, after performing the build, I’m getting a different file tree than you are. All of my pages are under the src folder. When I use the code provided in the example above, I receive the following error:
    Error reading template file, “build/pages/home/home.html”: Error: ENOENT: no such file or directory, open
    ‘/Users/pschup/Desktop/ForageProject/src/pages/home/build/pages/home/home.html’

    I can change the path to the relative path of simply ‘home.html’ since the .ts and the .html are in the same folder for the page. This addresses the error, however, the build simply displays a blank page

    • Ionic RC0 messed up a lot of things for a lot of people.

      As soon as it stablizes I will be modifying this tutorial to reflect. The core concepts will remain true though, just the file structures will be a bit different.

      Best,