Uncaught TypeError: Cannot read properties of undefined (reading 'state')

Uncaught TypeError: Cannot read properties of undefined (reading 'state')

Posted by Ervin Adams on August 30, 2022

Uncaught TypeError: Cannot read properties of undefined (reading 'state')

Uncaught TypeError: Cannot read properties of undefined (reading 'state')

Posted by Ervin Adams on August 30, 2022

If you get this error "Uncaught TypeError: Cannot read properties of undefined (reading 'state')"

The reason for that kind of error is most likely that the state is in a method that is not bound to the component.

Here is how you can bind the method:

Option 1. Bind method in construction

constructor(props) {
   super(props);
   this.state = {
      userName:"",
      password:"",
   };
   this.handleSubmit = this.handleSubmit.bind(this);
}

...

handleSubmit (e) {
  e.preventDefault();

  if(this.state.password === "" && this.state.userName === "") {
      alert("you cannot enter");
  }
}

Option 2. Use fat arrow method

handleSubmit = (e) => {
  e.preventDefault();

  if(this.state.password === "" && this.state.userName === "") {
      alert("you cannot enter");
  }
}