Fix – cannot read property setState of undefined

If you get cannot read property setState of undefined when writing a code in React, this article will fix your problem. The issue occurs because…

The post Fix – cannot read property setState of undefined appeared first on CodeSource.io.


This content originally appeared on CodeSource.io and was authored by Pandu Rijal Pasa

If you get cannot read property setState of undefined when writing a code in React, this article will fix your problem.

The issue occurs because the this keyword is not pointing out the right scope of the component. You can fix this by binding your function:

constructor(props) {
super(props);
  state = {};
  
  this.myFunction = this.myFunction.bind(this);
}

myFunction() {
  // your function here
}

Or in the latest (and simple) version, you can use arrow function to avoid binding things. Here is the example:

constructor(props) {
super(props);
  state = {};
}

myFunction = () => {
  // your function here
}

The post Fix – cannot read property setState of undefined appeared first on CodeSource.io.


This content originally appeared on CodeSource.io and was authored by Pandu Rijal Pasa


Print Share Comment Cite Upload Translate Updates
APA

Pandu Rijal Pasa | Sciencx (2021-02-20T07:46:26+00:00) Fix – cannot read property setState of undefined. Retrieved from https://www.scien.cx/2021/02/20/fix-cannot-read-property-setstate-of-undefined/

MLA
" » Fix – cannot read property setState of undefined." Pandu Rijal Pasa | Sciencx - Saturday February 20, 2021, https://www.scien.cx/2021/02/20/fix-cannot-read-property-setstate-of-undefined/
HARVARD
Pandu Rijal Pasa | Sciencx Saturday February 20, 2021 » Fix – cannot read property setState of undefined., viewed ,<https://www.scien.cx/2021/02/20/fix-cannot-read-property-setstate-of-undefined/>
VANCOUVER
Pandu Rijal Pasa | Sciencx - » Fix – cannot read property setState of undefined. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/02/20/fix-cannot-read-property-setstate-of-undefined/
CHICAGO
" » Fix – cannot read property setState of undefined." Pandu Rijal Pasa | Sciencx - Accessed . https://www.scien.cx/2021/02/20/fix-cannot-read-property-setstate-of-undefined/
IEEE
" » Fix – cannot read property setState of undefined." Pandu Rijal Pasa | Sciencx [Online]. Available: https://www.scien.cx/2021/02/20/fix-cannot-read-property-setstate-of-undefined/. [Accessed: ]
rf:citation
» Fix – cannot read property setState of undefined | Pandu Rijal Pasa | Sciencx | https://www.scien.cx/2021/02/20/fix-cannot-read-property-setstate-of-undefined/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.