setting ko observable inside a promise not working

45 Views Asked by At

I have a view model below (from an article about cloudkitjs). The problem is that the observables are not changed in the return from the db call. The page displays recCount as 3 even though the db call finds 40 records.

 function TILViewModel()
 {
    var self = this;
    console.log("get default container");
    var container = CloudKit.getDefaultContainer();


    var publicDB = container.privateCloudDatabase;

    self.myRecords = ko.observableArray();
    self.recCount = ko.observable(3);
    var recSet = [];
    // Fetch public records
    self.fetchRecords = function()
    {
        console.log("fetching records from " + publicDB);
        var query = { recordType: 'examRecord', sortBy: [{ fieldName: 'studyDate'}] };
  
        // Execute the query.
        return publicDB.performQuery(query).then(function(response)
        {
            if(response.hasErrors)
            {
               console.error(response.errors[0]);
               return;
            }
           var records = response.records;
           var numberOfRecords = records.length;
           if (numberOfRecords === 0)
           {
                console.error('No matching items');
                return;
           }
     
           console.log(records.length + " records")
          // self.myRecords(records); // this also fails      
          self.myRecords.push(recSet); // fails
          self.recCount = ko.observable(9); // fails
      });
  };
1

There are 1 best solutions below

1
On

self.recCount(numberOfRecords) should do the trick and, you should also do self.myRecords.push for each record, not push recSet that is empty;