I keep getting this error, and I don't know why, because everything I have tried don't work. Does anybody knows why this is not working and how it can work?
I get this undefined here:
this.setState({isAuthenticated: true})
Here is my code:
class Login extends Component{
constructor(props){
super(props);
this.state ={
email: '',
password: '',
isAuthenticated: false
};
function login(username, email){
sessionStorage.setItem('loginSessionUsername', username);
sessionStorage.setItem('loginSessionEmail', email);
this.setState({isAuthenticated: true})
}
}
render(){
const isAuthenticated = this.state.isAuthenticated;
if(isAuthenticated){
return(
<div>
<Servicedesk />
</div>
)
}
return(
<div id='Login' className='setVisible'>
<div>
<label>Emailadres</label>
<input type='text' placeholder='je email' onChange={ev => this.setState({email: ev.target.value})}/>
<label>Wachtwoord</label>
<input type='password' placeholder='je wachtwoord' onChange={ev => this.setState({password: ev.target.value})}/>
<br />
<button onClick={(event => this.handleClick(event))}>Submit</button>
</div>
</div>
)
}
}
export default Login;
You should use arrow function (see the docs), that will bind the context to your function, like this:
const login = ( username, email) => {
sessionStorage.setItem('loginSessionUsername', username);
sessionStorage.setItem('loginSessionEmail', email);
this.setState({isAuthenticated: true})
}
move your login function outside of your constructor.
class Login extends Component{
constructor(props){
super(props);
this.state ={
email: '',
password: '',
isAuthenticated: false
};
}
handleClick = () => {
sessionStorage.setItem('loginSessionUsername', this.state.username);
sessionStorage.setItem('loginSessionEmail', this.state.email);
this.setState({isAuthenticated: true})
}
render(){
const isAuthenticated = this.state.isAuthenticated;
if(isAuthenticated){
return(
<div>
<Servicedesk />
</div>
)
}
return(
<div id='Login' className='setVisible'>
<div>
<label>Emailadres</label>
<input type='text' placeholder='je email' onChange={ev => this.setState({email: ev.target.value})}/>
<label>Wachtwoord</label>
<input type='password' placeholder='je wachtwoord' onChange={ev => this.setState({password: ev.target.value})}/>
<br />
<button onClick={(event => this.handleClick())}>Submit</button>
</div>
</div>
)
}
}
export default Login;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With