Steven Klinger
Steven Klinger

Reputation: 284

Update ListView with db-models data

I would like to generate my view with my data created with db-models :

https://www.npmjs.com/package/react-native-db-models

But there is the problem : nothing appends, my view stay empty. 1 ) The size of db (for loop) is equal to 0 (but it must be 8 after my DB.bills.get_all().

Constructor

constructor(props) {
  super(props);
  var bdd = [];
  const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
  this.state = {
  dataSource: ds.cloneWithRows(bdd)
 };
}

ComponentDidMount()

componentDidMount() {
console.log("START");

let self = this;
var db = [];

DB.bills.get_all(function(result) {
  db = result;
  console.log(db);
});

  let newArray = self.state.dataSource._dataBlob.s1.slice();
  for(var i = 0; i<Object.keys(db).length ; i++){
    newArray[i] = {
      ...self.state.dataSource[i],
      field: JSON.stringify(db),
    };
    console.log("i : " + i + " db : " + db);
  }

  self.setState({dataSource: self.state.dataSource.cloneWithRows(newArray),
  });
        console.log("DS : ", this.state.dataSource);
  console.log("END");
}

There is the console.log(db) in my DB.bills.get_all()

Object {totalrows: 7, autoinc: 8, rows: Object}
autoinc : 8
rows : Object
 1 : Object
  creditor:"M. Alixe"
  month:"Décembre"
  picture:"https://cdn.pbrd.co/images/8YftpB3rQGA5S.png"
  price:"700"
  type:"Maquettes UI"
  year:"2016"
  _id:1
  __proto__:Object
2:Object
3:Object
4:Object
5:Object
6:Object
7:Object
__proto__:Object
totalrows:7
__proto__:Object

I'm on it since 2 days. Please help me ^^"

Upvotes: 0

Views: 74

Answers (1)

Nagender Singh
Nagender Singh

Reputation: 71

That's because your DB.bills.get_all function is asynchronous. By the time you get result, you have already calculated newArray and set your state. You need to wait for the result before calculating newArray and cloning your dataSource. Try putting the code after DB.bills.get_all inside the callback function.

Upvotes: 1

Related Questions