jesusWalks
jesusWalks

Reputation: 355

ReactJS. Firebase. TypeError: Cannot read property 'setState' of undefined

Below is a function that is called when a name is submitted. It goes to the firebase db and we then can see who is connected by looking at the db.

However, when I pull this data into an array of objects (users), I get stuck. I'm trying to push this data into this.state.names (array declared in the constructor state) but I just can't get my head round it.

The error message points to the function at the bottom of the code. Should the function be moved? Why is it not working? I've read many posts on 'this' but am struggling.

setName = e => {
    e.preventDefault()
    let name = this.state.name;
    let connectedRef = firebase.database().ref('.info/connected');

    connectedRef.on('value', (snapshot) =>{
      if (snapshot.val() === true) {
        // Connected
        const con = listRef.child(name);
        con.onDisconnect().remove();
        con.set(true);   //Write data (true) 
      }

      listRef.on("value", (snapshot) => {
        let users = [];
        snapshot.forEach( (user) => {
          users.push({
            id: snapshot.key,
            name: snapshot.val()
          })
        });
        setList(users);
      });
      function setList(users) {
        this.setState({
          names: users
        })
      }
    });
  }

Any ideas what I'm doing wrong?

Upvotes: 0

Views: 33

Answers (1)

lankovova
lankovova

Reputation: 1426

Normal functions have its own context. To be able to recieve correct this from the upper level, you need to modify your setList function to be arrow function. Like this:

const setList = (users) => {
  this.setState({
    names: users
  })
}

And also do not forget to lift it up, declaration should be before usage, since const variables doesn't hoist.

Upvotes: 1

Related Questions