Search code examples
javascriptreactjssetstate

Reactjs - Cannot read the property of undefined


I am trying to render a class component using conditional rendering. The class component has a state value that is by default set to false. In the class, a function called start() performs some operation and based on the results, it will call a function verifyTheIdentity() that has setState(). But I am not able to call the verifyTheIdentity() from start().

import React from "react";
import * as faceapi from "face-api.js";
import web3 from "../web3";

class recognize extends React.Component {
  constructor(props) {
    super();
    this.state = {
      verified: false
    }
    this.verifyTheIdentity = this.verifyTheIdentity.bind(this);
    // this.start = this.start.bind(this);
  }
  verifyTheIdentity() {
    this.setState(prevState => {
      return {
        verified: true
      }
    })
  }
  async start() {
    ///////////////////CODE FOR FACE RECOGNITION///////////////////////////////
    let name = result.toString();
    console.log(name);
    const pattern = new RegExp(/^unknown/)
    console.log(pattern.test(name))
    if (pattern.test(name) === false) {
      document.getElementById("verifier").disabled = false;
      document.getElementById("verifier").onClick = this.verifyTheIdentity;    //This is where I am going wrong.
    }
    else
      document.getElementById("verifier").disabled = true;

  })
})
    }
render() {
  return (
    <div>
      {this.state.verified == false ? <div><br /><br /><br /><br />
        <input type="file" id="imageUpload" /><br />
        <button disabled id="verifier" >Verify</button></div> :
        <div><br /><br /><br /><br /><p>Verified</p></div>}
    </div>

  )
}
}
export default recognize;

And this is the error I get.

Unhandled Rejection (TypeError): Cannot read property
'verifyTheIdentity' of undefined.

Solution

  • First of all, you do not need bind at all, if you use arrow function.

        constructor(props) {
            super();
            this.state = {
                verified: false 
            }
        }
        verifyTheIdentity = () => {
            //code
        }   
        start = async () => {
           // code 
        }
    

    Try this, it should work.

    or remove commented code, add in constructor (remove // from the line)

    this.start = this.start.bind(this);