0

I am trying to make a Login page and I am successful in some way. So here is my Login component:

    import React, { useState, useEffect } from "react";
import Axios from "axios";
import useForm from "../components/LoginForm/useForm";
import validate from "components/LoginForm/validate";
import redtruck from "../assets/img/red-truck.png";
import auth from "../Authentication/auth";

import { withRouter } from "react-router";

const Login = ({ submitForm, history }) => {
  const [isSubmitted, setIsSubmitted] = useState(false);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(false);
  const [login, setLogin] = useState(false);

  async function submitForm() {
    setIsSubmitted(true);
    try {
      await fetchLogin(values.email, values.password);
      if(login){
        auth.login(() => {
          history.push("/admin");
        });
      }
    } catch (e) {
      auth.login(() => {
        history.push("/");
      })
    }
  }

  const { handleChange, values, handleSubmit, errors } = useForm(
    submitForm,
    validate
  );

  useEffect(() => {
    if (localStorage.getItem("user-info")) {
      submitForm();
    }
  }, []);
  const fetchLogin = async (email, password) => {
    try {
      setLoading(true);
      const res = await Axios({
        method: "POST",
        url: `url`,
        headers: {
        },
        data: {
          user_email: email,
          user_password: password,
        },
      });
      if (res.status === 200) {
        setLogin(true);
        localStorage.setItem("user-info", JSON.stringify(res.data));
      }
      setLoading(false);
    } catch (err) {
      setError(err.message);
      setLoading(false);
    }
  };

  return (
    <>
      <div>
        <div className="form-container">
          <div className="form-content-left">
            <img className="form-img" src={redtruck} alt="spaceship" />
          </div>
          <div className="form-content-right">
            <h1>SIGN IN</h1>
            <form className="form" onSubmit={handleSubmit}>
              <div className="form-inputs">
                <label htmlFor="email" className="form-label">
                  Email address
                </label>
                <input
                  id="signin-email"
                  type="email"
                  name="email"
                  placeholder="Enter email"
                  className="form-input"
                  value={values.email}
                  onChange={handleChange}
                />
                {errors.email && <p>{errors.email}</p>}
              </div>
              <div className="form-inputs">
                <label htmlFor="password" className="form-label">
                  Password
                </label>
                <input
                  id="signin-password"
                  type="password"
                  name="password"
                  placeholder="Password"
                  className="form-input"
                  value={values.password}
                  onChange={handleChange}
                />
                {errors.password && <p>{errors.password}</p>}
                {login ? "" : <p>The password or the email is wrong</p>}
              </div>
              <button
                variant="primary"
                type="submit"
                className="form-input-btn"
              >
                LOGIN
              </button>
            </form>
          </div>
        </div>
      </div>
    </>
  );
};

export default withRouter(Login);

So the login state is set to true when email and password are right for the user. Later I want to use it when redirecting page to "/admin". But my problem is I have to click twice to login in the first place. Besides I am not sure, if the catch part is right:

catch (e) {
      auth.login(() => {
        history.push("/");
      })
    }

So I would be really glad, if you can give me some hint about it.

Thanks...

magic bean
  • 687
  • 13

1 Answers1

0

it is not that you have to press twice, you can check component state, sometimes React batches setState and then update value. You can look at this setState doesn't update the state immediately