Search code examples
javascripthtmlibm-mobilefirstjsonstore

Save multiple times at almost the same time in workligth JSONStore


I want to add to JSONStore by using a for cycle

so i call the saveToJSON() function inside the for with a length more than 500, but it doesnt add, and in console it shows succes but when i look in the jsonstore theres nothing,and number of the cycle for times that i called to add to jsonstore is in a red bubble in console.

function saveToJSON(object) {

var data ={

    title :     object.title, 
    subtitle:   object.subtitle,         

  };

var options = {}; //default
WL.JSONStore.get('MyDataCollection').add(data, options)
  .then(function () {
    //handle success
    console.log("add JSONStore success");

    })
  .fail(function (errorObject) {
    //handle failure
    console.log("add JSONStore failure");

});

}

Solution

  • Try creating an array with the data you want to add and then passing that to JSONStore's add API. Remember to make sure that WL.JSONStore.init has finished successfully before calling the add API.

    Example pseudocode:

    //This is the data you want to add, you probably get this from a network call
    var someData = [{title: 'hello'}, {title: 'world'}];
    
    //This is an array that you will pass to JSONStore's add API
    var someArray = [];
    
    //Populate the array with data you want to pass to JSONStore's add API
    for (var i = 0; i < someData.length; i++) {
        someArray.push(someData[i]);
    }
    
    //Add data inside someArray to the collection called: MyDataCollection
    WL.JSONStore.get('MyDataCollection').add(someArray)
    .then(function () {
    
        //Do a find all operation on the collection called: MyDataCollection
        return WL.JSONStore.get('MyDataCollection').findAll();
    })
    .then(function (res) {
    
        //Print all the data inside the collection called: MyDataCollection
        console.log(JSON.stringify(res));
    });
    
    //You may want to add .fail(function(){...}) to handle errors.