0

React this become undefined after a function is called by a component, before the this is not undefined. I cannot change the state.

export default class Chart extends React.Component {

   constructor(props) {
    super(props);
    var obj=JSON.stringify(this.props.data);
     this.state={data: obj};
   }

   insert(){

     //here it shows undefined
     console.log(this)
     var json=JSON.parse(this.state.data);
     //...
   }

   render() {
     //here shows non-undefined this
     console.log(this)
     return(
     //...
      //here calls the fuction that causes the error
     <button className="btn" onClick={this.insert}>Add New</button>
     </div>
     //...
     );
   }

Here is the error

Uncaught TypeError: Cannot read property 'state' of undefined
at insert (Chart.js:72)

enter image description here

Israel Martins
  • 178
  • 1
  • 10

1 Answers1

1

You are losing scope here:

onClick={this.insert}

Just do

onClick={() => this.insert()}

to preserve it.

Jonas Wilms
  • 106,571
  • 13
  • 98
  • 120