0

This is my function in class:

loadFeed = () => {
    this.setState=({
        refresh: true,
        collection: []
    });

    var that = this;

    database.ref('collection').orderByChild('date').once('value').then(function(snapshot) {
        const exists = (snapshot.val() !== null);
        if(exists) data = snapshot.val();
        var temp = that.state.employees;

        for(var item in data){
            var Obj = data[photo];

            database.ref('users').child(Obj.name).once('value').then(function(snapshot){
                const exists = (snapshot.val() !== null);
                if(exists) data = snapshot.val();

                temp.push({
                    id: key,
                    name: Obj.name
                });

                that.setState({
                    refresh: false,
                    loading: false
                });

            }).catch(error => console.log(error)); 
        }
    }).catch(error => console.log(error));
}

In above code I am getting this error:

that.setState is not a function.

  (In 'that.setState({
            refresh: false,
            loading: false
          })', 'that.setState' is an instance of Object)
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Rahul
  • 11
  • 2

2 Answers2

1
this.setState=({
    refresh: true,
    collection: []
});

should be

this.setState({
    refresh: true,
    collection: []
});
Phil Rukin
  • 450
  • 2
  • 17
0

Instead of using var that = this; you should bind this into the context in which you are trying to use this.

From https://developer.mozilla.org :

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

const module = {
  x: 42,
  getX: function() {
    return this.x;
  }
}

const unboundGetX = module.getX;
console.log(unboundGetX()); // The function gets invoked at the global scope
// expected output: undefined

const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());
// expected output: 42

If you are unfamiliar with that, you should look into what binding is in JavaScript:

Evgenii Klepilin
  • 695
  • 1
  • 8
  • 21