Giri Allada
Giri Allada

Reputation: 11

Why isn't this.setState working here?

snapshot.forEach(function(childSnapshot) {
  groupRef.child(childSnapshot.key).once("value", (snap) => {
    this.setState.bind({
      expenses: this.state.expenses.concat(snap.val()),
    });
  })
})

The error which I get is

undefined is not an object (evaluating '_this2.setState')

The state has been declared in the following way

constructor(props) {
  super (props);
  this.state = {
    expenses: [],
  };
}

Upvotes: 0

Views: 85

Answers (1)

nanobar
nanobar

Reputation: 66355

It's because you're not calling or using bind correctly and you are referencing this which is different in the context you created by calling forEach with a traditional function callback. The first argument to bind is the context not arguments.

In this case just avoid it and use arrow functions so this is still your component reference.

snapshot.forEach((childSnapshot) => {
  groupRef.child(childSnapshot.key).once("value", snap =>
    this.setState(state => ({ expenses: [ ...state.expenses, snap.val()] }))
  );
});

Note that you should use the callback style of setState as above when referencing existing state, since setState is asynchronous by the time your state is set it might have changed especially when setting in a loop in an async callback.

Upvotes: 5

Related Questions