mardi 18 août 2020

Why state is undefined? [duplicate]

I have a React component like this:

import React, { Component } from "react";
import { Button, FormGroup, FormControl, FormLabel } from "react-bootstrap";

import { Auth } from "aws-amplify";

export default class Login extends Component {
  state = {
    email: "",
    pw: "",
  };
  validateForm() {
    return this.state.email.length > 0 && this.state.pw.length > 0;
  }

  async handleSubmit(e) {
    e.preventDefault();
    console.log(this.state.email, this.state.pw);
    try {
      await Auth.signIn(this.state.email, this.state.pw);
      alert("Logged in");
    } catch (e) {
      alert(e.message);
    }
  }

  render() {
    return (
      <div className="Login">
        <form onSubmit={this.handleSubmit}>
          <FormGroup controlId="email" bsSize="large">
            <FormLabel>Email</FormLabel>
            <FormControl
              autoFocus
              type="email"
              onChange={(e) => this.setState({ email: e.target.value })}
            />
          </FormGroup>
          <FormGroup controlId="password" bsSize="large">
            <FormLabel>Password</FormLabel>
            <FormControl
              onChange={(e) => this.setState({ pw: e.target.value })}
              type="password"
            />
          </FormGroup>
          <Button
            block
            bsSize="large"
            disabled={!this.validateForm()}
            type="submit"
          >
            Login
          </Button>
        </form>
      </div>
    );
  }
}

I don't know why every time the handleSubmit function runs, it throws "Cannot read property 'state' of undefined", even though the state is updated every time user changes it. Everything works just fine when I change the email input or password input, but when I click the submit button, it just throw that error again




Aucun commentaire:

Enregistrer un commentaire