1

I get "TypeError: Cannot read property 'setState' of undefined" if I try to call setState in a function (edit or save). It works if I declare an arrow function instead, but I do not understand why?

import React, { Component } from 'react';

class Note extends Component {
    constructor(props) {
        super(props);
        this.state = {
            editing: false
        }
    }

    edit (){
        this.setState({ editing: true })
    }

    save() {
        this.setState({ editing: false })
    }

    renderEditNote() {
        return (
            <div className="note">
                <textarea></textarea>
                <button onClick={this.save}>SAVE</button>
            </div>
        )
    }

    renderDisplayNote() {
        return (
            <div className="note">
                <p>{this.props.children}</p>
                <span>
                    <button onClick={this.edit}>Edit</button>
                    <button onClick={this.remove}>X</button>
                </span>
            </div>
        )
    }

    render() {
        return this.state.editing ? this.renderEditNote() : this.renderDisplayNote()
    }
}

export default Note
netjens
  • 55
  • 8

2 Answers2

0

To make it works, you should do

this.save.bind(this)
this.edit.bind(this)
this.remove.bind(this)

You have not bind it yet, so the this in your method edit(), save() and remove() is not the Note class. You can do console.log(this) in those methods to understand why

dnp1204
  • 471
  • 5
  • 14
0

You need to bind this for edit and save functions so it doesn't get lost when called-back by the onClick.

For example:

 <button onClick={this.edit.bind(this)}>Edit</button>

Or you can do it in the constructor as:

this.edit = this.edit.bind(this);

Tareq
  • 5,283
  • 2
  • 15
  • 18