Home > Mobile >  TypeError: Cannot read properties of undefined (reading 'state') reactjs
TypeError: Cannot read properties of undefined (reading 'state') reactjs

Time:09-27

I am trying to console log the username and password in onClick in reactjs but I am getting the TypeError. I have definded authenticate function under the constructor of the class. Below is the complete code. Can anyone guide me here?

 authenticate(e){
        e.preventDefault();
        var details = {
            "email" : this.state.username,
            "password" : this.state.password
        }
        alert(details.username   details.password);


 <input type="email" onChange = {(event,newValue) => this.setState({username:newValue})} className="form-control" name="email" placeholder="Enter your Email" required="required" />

<input type="password" onChange = {(event,newValue) => this.setState({password:newValue})} className="form-control" name="password" placeholder="Enter your Password" required="required" />

<button className="btn w-100 mt-3 mt-sm-4" onClick={this.authenticate} type="submit">Sign In</button>

CodePudding user response:

var details = {
            "email" : this.state.username,
            "password" : this.state.password
        }
        alert(details.username   details.password);

In this right here, you call for details.username but details will only have the keys email and password.

So basically, details.username is undefined, and you can't read that property.

Try changing it to

var details = {
                "email" : this.state.username,
                "password" : this.state.password
            }
            alert(details.email   details.password);
  • Related