0

It is my first day with react native, I am working with mangodb, I stored record in db and fetched record, now I want to show in flatlist, and need to setState() but it throws error of undefined

db.find({}, function (err, docs) {
      this.setState({ dataSource: docs });   
});

docs is array of users and I am able to print data in console, its working, but problem is how do I set this data in datasource using setState.

Gleb Kostyunin
  • 2,923
  • 1
  • 16
  • 33

1 Answers1

6

It's related to the way you call setState. this inside the context of your function is not pointing to the component class. One way to solve it is to use an arrow function:

db.find({}, (err, docs) => {
      this.setState({ dataSource: docs });   
});

If you can't use arrow functions, you can do the binding of your function to the outside context manually:

function cb (err, docs) {
      this.setState({ dataSource: docs });   
}

db.find({}, cb.bind(this));

The logic behind this keyword in javascript is discussed in detail in this question: How does the "this" keyword work? Or in this amazing book by Kyle Simpson: YDKJS: this & object prototypes

Gleb Kostyunin
  • 2,923
  • 1
  • 16
  • 33