3gwebtrain
3gwebtrain

Reputation: 15303

How to preserve `LokiJS` data in `localstorage`

my data base is not preserved in local storage. any one help me here? I guess that, lokijs will preserve the data in localstorage by default. But after refresh I am not getting the updated datas.

here is my code :

jQuery(document).ready(function($) {

    var db = new loki("test", {
        autosave: true, //setting to save
        autosaveInterval: 1000
    });

    var children = db.addCollection('children')
//adding defualt datas
    children.insert({name:'Sleipnir', legs: 8})
    children.insert({name:'Jormungandr', legs: 0})
    children.insert({name:'Hel', legs: 2});



    $("#local").on("click", function(e){

        e.preventDefault();

        var callback = function( data ){
            console.log("call back data", data );
        }

        $.mockjaxSettings.namespace = "";
        myCaller( callback );

    })

    $("#remote").on("click", function(e){

        e.preventDefault();

        $.mockjaxSettings.namespace = "///";
        myCaller();


    });

    $("#getData").on("click", function(e){

        e.preventDefault();

        var child = children.find();

        console.log( "children", child );

    });

    $("#insertData").on("click", function(e){

        e.preventDefault();
        //inserting new data, but after refresh i am not getting it!!!
        children.insert({name:'Mohamed Arif', legs: 2});

    })


});

Upvotes: 1

Views: 627

Answers (1)

fleau
fleau

Reputation: 56

Your data are preserved in local storage, you just erase them every time you load a page with var children = db.addCollection('children')

Replace it by :

var children
db.loadDatabase({}, () => {
  children = db.getCollection('children')
  if(!children) {
    children = db.addCollection('children')
  }
})

So with this, if your collection doesn't exist you create it and you don't erase it if it already exists.

I quickly made a plunker that does what you asked : https://plnkr.co/edit/eOgc1ZoQioaI4JYpeggY

Upvotes: 1

Related Questions