localforage

How to initialize localForage for mobile app


I'm new to mobile development and plan to build an app using plain HTML & jQuery, with Onsen UI.

I read that we can use localForage as a database and have a few questions.

  1. Is it mandatory to have a database name for my app. If no, then other apps in mobile may also be using localForage. Will the DB be same then for all apps.

  2. The document here says, config should be called before each action. So, is it ok if it is initialized on page load like this:

    $(document).ready(function(){
    localforage.config({
    name : 'myApp',
    version : 1.0,
    storeName : 'keyvaluepairs'
    });
    });

or should it be declared before each action (get, set, clear etc.)

  1. How can we know that the action is triggering the desired database, as it is not specified in the action methods.

  2. Is it mandatory to have a store name.


Solution

    1. Is it mandatory to have a database name for my app. If no, then other apps in mobile may also be using localForage. Will the DB be same then for all apps.

    A: Yes and no. It is in fact mandatory to have a database name. However if you leave it unset, the default value "localforage" is used.

    1. The document here says, config should be called before each action. So, is it ok if it is initialized on page load like this ...

    A: Yes, it totally fine to init in $(document).ready(cb). In fact it's fine to "initialize" at any time, as long as you make sure it happens before the first ever call to any real action (setItem/getItem, etc.).

    1. How can we know that the action is triggering the desired database, as it is not specified in the action methods.

    A: localforage can have multiple instances, whereas each instance is bound to only one database, (more precisely, it's bound to a specific store of that specific database). You know the action is targeting a specific database, because these actions are methods of a specific instance. No ambiguity here.

    I personally suggest you name your instance explicitly:

    var myAppDb = localforage.createInstance({
      // these are the same options accepted by localforage.config()
      name: 'myApp',
      version : 1.0,
      storeName : 'keyvaluepairs'
    });
    
    myAppDb.setItem('foo', 'bar');
    

    This way you're 100% sure the action is fired on "myApp" database ;-)

    1. Is it mandatory to have a store name.

    Again, yes and no. But wait, hear me out, this one is a bit tricky.

    Whereas the default database is actually named "localforage", store in localforage has this strange internal concept of un-named default store. I personally find it very confusing. And it behaves quite quirky when you use LOCALSTORAGE as driver.

    So the rule of thumb is always name your store. Just treat it like mandatory. If you have only one store in one database, maybe name it "default". Sound better than "keyvaluepairs" don't you think?