0

I want to update my "userSuccessfullLoggedIn" in success login state but it won't updating. It update the state if username and password are incorrect but it is not updating when username and password are true I cant find the problem please help me.

import React, { Component } from "react";
import LoginResponse from "./LoginResponse";

class Login extends Component {
  constructor() {
    super();
    this.state = {
      username: "",
      password: "",
      loginStatus: "",
      userSuccessfullLoggedIn: "",
    };
  }

  onChange = (event) => {
    this.setState({
      [event.target.name]: event.target.value,
    });
  };

  loginResponse = () => {
    if (this.state.username === "jarvis" && this.state.password === "jarvis") {
      console.log("Successfull");
      this.setState({
        loginStatus: true,
        userSuccessfullLoggedIn: true,
      });
      sessionStorage.setItem("user", this.state.username);
      this.props.history.push(`/welcome/${this.state.username}`);
    } else {
      console.log("Wrong");
      this.setState({
        loginStatus: false,
        userSuccessfullLoggedIn: false,
      });
    }
  };

  render() {
    return (
      <div>
        <div className="login-form">
          <h1 className="text-center"> LOGIN </h1>
          <div className="form-group">
            <input
              placeholder="Username"
              className="form-control"
              type="text"
              name="username"
              value={this.state.username}
              onChange={this.onChange}
            />
          </div>
          <div className="form-group">
            <input
              placeholder="Password"
              className="form-control"
              type="password"
              name="password"
              value={this.state.password}
              onChange={this.onChange}
            />
          </div>
          <div className="form-group">
            <button className="btn btn-primary" onClick={this.loginResponse}>
              LOGIN
            </button>
          </div>
          <LoginResponse status={this.state.loginStatus} />
        </div>
      </div>
    );
  }
}
export default Login;

Console

enter image description here

It is going inside Success block but it is not updating the state from false to true

  • 2
    Works for me: https://codesandbox.io/s/flamboyant-chaum-542c6?file=/src/App.js – lux Jul 28 '20 at 06:59
  • setState is async in nature, put a call back and check the status what you are getting i.e this.setState({ loginStatus: true, userSuccessfullLoggedIn: true, }, () => { console.log(this.state.loginStatus); }); – Yerrapotu ManojKiran Jul 28 '20 at 06:59

1 Answers1

1

setState is async in nature, put a call back and check the status what you are getting i.e

this.setState({ loginStatus: true, userSuccessfullLoggedIn: true, }, () => {
 console.log(this.state.loginStatus); 
});