Ivan Erlic Ivan Erlic - 1 month ago 15
React JSX Question

React Form onChange doesn't update state

I am getting a wierd behaviour when i input into my password

<input/>
. Every time I input something into it the state doesn't change but it console.logs. The same thing doesn't happen with email field and when i try to submit the form the password is empty... What am I doing wrong?

This is my react component:

5 export default class Login extends React.Component {
6 state: {
7 email: string,
8 password: string,
9 };
10
11 handleEmailChange: (e: any) => void;
12 handlePasswordChange: (e: any) => void;
13 handleButtonPress: () => void;
14
15 constructor() {
16 super();
17 this.state = { email: '', password: '' };
18
19 this.handleEmailChange = this.handleEmailChange.bind(this);
20 this.handlePasswordChange = this.handleButtonPress.bind(this);
21 this.handleButtonPress = this.handleButtonPress.bind(this);
22 };
23
24 handleEmailChange(e: any) {
25 this.setState({ email: e.target.value });
26 };
27
28 handlePasswordChange(e: any) {
29 this.setState({ password: e.target.value });
30 };
31
32 handleButtonPress() {
33 axios.post('/api/users/login', {
34 email: this.state.email,
35 password: this.state.password,
36 })
37 .then((response: any) => {
38 console.log(response.data);
39 })
40 .catch((error: any) => {
41 console.log(error);
42 });
43 };
44
45 render() {
46 return (
47 <div>
48 <input
49 type="email"
50 onChange={this.handleEmailChange}
51 placeholder="Enter email"
52 />
53 <input
54 type="password"
55 onChange={this.handlePasswordChange}
56 placeholder="Enter password"
57 />
58 <button onClick={this.handleButtonPress}>
59 Login!
60 </button>
61 </div>
62 );
63 }
64 }


Here is the screenshot of what happens when i go the enter the password:
enter image description here

Thank you in advance.

Answer

error in line-20.

this.handlePasswordChange = this.handleButtonPress.bind(this);

it should be

this.handlePasswordChange = this.handlePasswordChange.bind(this);
Comments