Untitled

mail@pastecode.io avatar
unknown
javascript
2 years ago
1.6 kB
9
Indexable
Never
 const [values, setValues] = useState({ username: "", password: "" });
 const [warning, setWarning] = useState({ username: "", password: "" });

   const handleLogin = (username, password) => {
    axios
      .post("/login", {
        username,
        password,
      })
      .then((response) => {
        if (response.status === 200) {
          setUser(response.data.user);
          navigate("/");
        }
      })
      .catch((error) => {
        if (error.response) {
          if (error.response.status === 401) {
            setWarning({
              username: "Invalid username or password",
              password: "Invalid username or password",
            });
          } else {
            setError("Server is offline, try again later");
          }
        } else if (error.request) {
          setError("Access denied, try again later");
        } else {
          setError("Something went wrong, try again later");
        }
      });
  }

 const handleSubmit = (e) => {
    e.preventDefault();

    if (values.username.length > 0 && values.password.length > 0) {
      handleLogin(values.username, values.password);
    } else if (values.username.length === 0 && values.password.length === 0) {
      setWarning({
        username: "Username is required",
        password: "Password is required",
      });
    } else if (values.username.length === 0) {
      setWarning({
        username: "Username is required",
        password: "",
      });
    } else if (values.password.length === 0) {
      setWarning({
        username: "",
        password: "Password is required",
      });
    }
  };