javascript - Cannot setState inside callback -
following code used set state.
handleaddnewquiz(event){ this.quiz = new quiz(this.db, this.newquizname, function(err, affected, value){ if(!err){ this.setstate( { quiz : value}); // error: cannot read property 'setstate' of undefined } }); event.preventdefault(); };
rven though database created successfully, cannot call this.state
, it's undefined.
i tried:
self = this; handleaddnewquiz(event){ this.quiz = new quiz(this.db, this.newquizname, function(err, affected, value){ if(!err){ self.setstate( { quiz : value}); // error: self.setstate not function } }); event.preventdefault(); };
but still fails, tried a = this
, , use a.setstate
, still no luck.
how can solve this?
use arrow function
bind
context
, use this:
handleaddnewquiz(event){ this.quiz = new quiz(this.db, this.newquizname, (err, affected, value) => { if(!err){ this.setstate( { quiz : value}); } }); event.preventdefault(); };
or use .bind(this)
callback method
, this:
handleaddnewquiz(event){ this.quiz = new quiz(this.db, this.newquizname, function(err, affected, value){ if(!err){ this.setstate( { quiz : value}); } }.bind(this)); event.preventdefault(); };
the way using work, save reference of this
inside handleaddnewquiz
method, way:
handleaddnewquiz(event){ let self = this; //here save reference of this.quiz = new quiz(this.db, this.newquizname, function(err, affected, value){ if(!err){ self.setstate( { quiz : value}); } }); event.preventdefault(); };
Comments
Post a Comment