0

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?

1 Answer 1

2

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));
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.