Teresa
Teresa

Reputation: 373

Cannot read property 'someFunction' of null for 'someFunction' within onClick

I am rendering a list of items retrieved from Firebase. For each item, I render a div, that includes a button that removes said item.

Relevant code:

constructor(props){
    // Pass props to parent class
    super(props);

    this.removeItem = this.removeItem.bind(this);
    this.getList = this.getList.bind(this); 
    ...
}

removeItem(key) {
    this.ref(key).remove()
}

getList() {
    var list = []
    this.ref.on("value", function (snapshot) {
        for (var key in snapshot.val()) {
            list.push(<div class="todo-item">{snapshot.val()[key]} <button onClick={() => this.removeItem(key)}> X </button> </div>)
        }
    }, function (error) {
        console.log("Error: " + error.code);
    });
    return(list)
}

render() {
    return (
        <div class="todolist">
            .....
            {this.getList()}
        </div>
    )
}

The list of items and their remove buttons renders fine. However, when clicking the remove button, I get a TypeError: Cannot read property 'removeItem' of null

As removeItem is a function of this, I assume that this is not properly bound and thus null.

However, I bound both functions removeItem and getList in the constructor.

Does someone know where I am going wrong?

Upvotes: 0

Views: 55

Answers (1)

Anand Undavia
Anand Undavia

Reputation: 3543

This is the most common problem of context being lost when this is accessed from anonymous function.

To get around this,

Use arrow functions:

this.ref.on("value", (snapshot) => { ... }, (error) => { ... });

OR
Use bind(this)

this.ref.on("value", function (snapshot) { ... }.bind(this), function (error) { ... }.bind(this));

Upvotes: 2

Related Questions