Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

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

TwitterFacebookRedditLinkedInHacker News

A few years ago I wrote an article called Use ngStorage for all Your AngularJS Local Storage Needs, which was intended to be for AngularJS in general. However, I understand many readers were using it in their hybrid Apache Cordova or Ionic Framework applications. There is nothing wrong with this. However, ngStorage is a wrapper for HTML5 local storage which is known to have compatibility issues under certain circumstances. That said, came across localForage, a library by Mozilla, which claims to be a wrapper for local storage, WebSQL, and IndexedDB, offering maximum compatibility.

We’re going to take a look at including localForage in an Ionic Framework Android and iOS application for storing data.

Before getting too far ahead of myself, I actually stumbled upon localForage via a recommendation from Nolan Lawson who was a guest in my podcast, PouchDB and its Usefulness in Development. He said that if you need a local database with no intentions of sync, localForage is a solid choice.

Creating a New Ionic Framework iOS and Android Project

To make this guide easy to understand, we’re going to start a new project and work our way up. This project will be a very simple list of people where we can add new people to the list. This list is saved to localForage and read from as necessary.

Ionic Framework localForage Demo

To create a new project, execute the following from your Terminal (Linux and Mac) or Command Prompt (Windows):

ionic start ForageProject blank
cd ForageProject
ionic platform add ios
ionic platform add android

There are a few things to note in the above commands. First, you’ll notice we are creating an Ionic Framework 1 project, not an Ionic 2 project. We are adding the iOS platform, but if you’re not using a Mac, you cannot build for iOS.

If you’re looking to use localForage in Ionic 2, you should read my other tutorial on the subject.

Including the localForage JavaScript Dependency from Mozilla

To make this library possible in our project, it must be downloaded and included. For this example I’ll be using version 1.4.2 of the library found here. If you’re up for the adventure, try to use the latest version.

After you’ve downloaded a ZIP archive of the release, extract it and look for the dist/localforage.min.js file. This file should be placed in the www/js file of your project.

With the file placed, open your project’s www/index.html file and include the following line:

<script src="js/localforage.min.js"></script>

The above line should be placed right below the include for the cordova.js file. At this point we should be ready to start developing with this new storage form.

Using the localForage Library in Your Ionic Framework Project

We’re going to focus on two particular files. One file will contain all of our AngularJS logic and the other will contain all of our HTML UI code. As previously stated, the project is meant to be very simple.

Starting with the AngularJS code, open the project’s www/js/app.js file and include the following code:

angular.module('starter', ['ionic'])

.run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
        if(window.cordova && window.cordova.plugins.Keyboard) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            cordova.plugins.Keyboard.disableScroll(true);
        }
        if(window.StatusBar) {
            StatusBar.styleDefault();
        }
    });
})

.controller("ExampleController", function($scope, $ionicPopup) {
    $scope.people = [];
    localforage.getItem("people").then(function(result) {
        $scope.people = result ? result : [];
        $scope.$apply();
    }, function(error) {
        console.log("ERROR: ", error);
    });
    $scope.save = function() {
        $scope.data = {};
        var myPopup = $ionicPopup.show({
            template: '<input type="text" ng-model="data.firstname" placeholder="First Name"><br /><input type="text" ng-model="data.lastname" placeholder="Last Name">',
            title: "Add Person",
            subTitle: "Add a new person to the list with a first and last name.",
            scope: $scope,
            buttons: [
                { text: 'Cancel' },
                {
                    text: '<b>Save</b>',
                    type: 'button-positive',
                    onTap: function(e) {
                        if (!$scope.data.firstname || !$scope.data.lastname) {
                            e.preventDefault();
                        } else {
                            $scope.people.push({
                                firstname: $scope.data.firstname,
                                lastname: $scope.data.lastname
                            });
                            localforage.setItem("people", $scope.people);
                        }
                    }
                }
            ]
        });
    }
});

There is a lot going on in the above code, so it is best that we break it down.

When creating an Ionic Framework project, the following is part of the core template and not something that we add ourselves:

angular.module('starter', ['ionic'])

.run(function($ionicPlatform) {
    $ionicPlatform.ready(function() {
        if(window.cordova && window.cordova.plugins.Keyboard) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            cordova.plugins.Keyboard.disableScroll(true);
        }
        if(window.StatusBar) {
            StatusBar.styleDefault();
        }
    });
})

What we add is the controllers, or in our scenario, the ExampleController. When this controller is first triggered, we load whatever is currently stored in localForage:

localforage.getItem("people").then(function(result) {
    $scope.people = result ? result : [];
    $scope.$apply();
}, function(error) {
    console.log("ERROR: ", error);
});

If the key does not exist, a null will be returned which is why we’re using a ternary operator. We want to be working with an array, not a null. To refresh the UI we call $apply() on the application scope.

Now we do have a function called save, but the code that sits in it is mostly taken from the Ionic Framework documentation for $ionicPopup. What we care about is the following:

$scope.people.push({
    firstname: $scope.data.firstname,
    lastname: $scope.data.lastname
});
localforage.setItem("people", $scope.people);

The $scope.data.firstname and $scope.data.lastname taken from the prompt will be pushed into our people scope and then that scope is saved. Remember, localForage can save anything without first having to serialize or parse.

Now let’s take a quick look at the HTML UI that goes with this logic. Open the project’s www/index.html file and include the following markup:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
        <title></title>

        <link href="lib/ionic/css/ionic.css" rel="stylesheet">
        <link href="css/style.css" rel="stylesheet">

        <script src="lib/ionic/js/ionic.bundle.js"></script>

        <script src="cordova.js"></script>
        <script src="js/localforage.min.js"></script>
        <script src="js/app.js"></script>
    </head>
    <body ng-app="starter">
        <ion-pane ng-controller="ExampleController">
            <ion-header-bar class="bar-stable">
                <h1 class="title">Ionic Blank Starter</h1>
                <button class="button" ng-click="save()">Add</button>
            </ion-header-bar>
            <ion-content>
                <ion-list>
                    <ion-item ng-repeat="person in people">
                        {{person.firstname}} {{person.lastname}}
                    </ion-item>
                </ion-list>
            </ion-content>
        </ion-pane>
    </body>
</html>

Above is the same HTML file that we included the localForage library to. Above is just the complete version of it. Notice that we are creating an ion-list and repeating over each item in the array to present on the screen. Just basic UI stuff to match our logic file.

At this point the application should be good to go!

Conclusion

You just saw how to include Mozilla’s localForage JavaScript library in your Ionic Framework mobile application. This library is great because not only is it more compatible than using local storage, but you can save any kind of data to it without parsing or serializing the data first. This guide was for Ionic Framework 1, but if you’re interested in seeing how it’s done with Ionic 2, check out my other tutorial on the topic.

Nic Raboy

Nic Raboy

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