I am new to reactjs. I have taken sample code from the react documentation (https://facebook.github.io/react/docs/forms.html) and modified it very slightly to create the following class:
class LoginView extends React.Component {
constructor(props) {
super(props);
this.state = {email: '',
password: ''};
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(event) {
alert(this.state.email);
this.setState({email: event.target.email});
this.setState({password: event.target.password});
}
handleSubmit(event) {
alert(this.state.email);
var response = fetch('http://0.0.0.0:5000/v1/authtoken/', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password,
})
}).then((response) => response.json())
var token = response.token
alert([token])
event.preventDefault();
}
render() {
return (
<div className="login-form">
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="email">Email address:</label>
<input type="email" className="form-control" id="email" value={this.state.email} onChange={this.handleChange}/>
</div>
<div className="form-group">
<label htmlFor="pwd">Password:</label>
<input type="password" className="form-control" id="pwd" value={this.state.password} onChange={this.handleChange}/>
</div>
<div className="checkbox">
<label><input type="checkbox"/> Remember me</label>
</div>
<button type="submit" className="btn btn-default">Submit</button>
</form>
</div>
);
}
}
export default LoginView
The purpose of the class is to present a login form which will post the value of the email and password fields to an endpoint. I am pulling my hair out over the way the this.state
object is behaving.
Note that there is an alert in both handleSubmit
and handlechange
. These alerts should contain the value of the email field, but they instead contain the value undefined
. What is confusing me is that the fields themselves, which also present values from this.state.email
, actually work. This means that state is somehow being saved, but it just isn't available within the functions.
I've been pouring over this for hours and am at a loss as to how I could be getting this behavior. Any help would be very appreciated.