diff --git a/src/app/login/page.tsx b/src/app/login/page.tsx index fbdf953..6831f70 100644 --- a/src/app/login/page.tsx +++ b/src/app/login/page.tsx @@ -5,67 +5,90 @@ import { Card } from "@/components/ui/card"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import axios from "axios"; -import { useState } from "react"; import Cookies from "js-cookie"; import { useRouter } from "next/navigation"; +import { useRef, useState } from "react"; export default function Login() { - const [username, setUsername] = useState(""); - const [password, setPassword] = useState(""); + const formRef = useRef(null); const [error, setError] = useState(""); + const [canSubmit, setCanSubmit] = useState(false); const router = useRouter(); const login = () => { setError(""); - axios({ - method: "post", - url: "/api/auth", - data: { - username, - password, - }, - }) + + const form = formRef.current; + if (!form) return; + + const username = (form.elements.namedItem("username") as HTMLInputElement) + ?.value; + const password = (form.elements.namedItem("password") as HTMLInputElement) + ?.value; + + if (!username || !password) return; + + axios + .post("/api/auth", { username, password }) .then((r) => { Cookies.set("session_id", r.data.sessionId); router.replace("/dashboard"); }) .catch((e) => { - setError(e.response.data.message); + setError(e.response?.data?.message || "Login failed"); }); }; + const handleInput = () => { + const form = formRef.current; + if (!form) return; + + const username = (form.elements.namedItem("username") as HTMLInputElement) + ?.value; + const password = (form.elements.namedItem("password") as HTMLInputElement) + ?.value; + + setCanSubmit(!!username && !!password); + }; + return (
- -

Login

- - { - setUsername((e.target as any).value); - }} - /> - - { - setPassword((e.target as any).value); - }} - onKeyDown={(e) => { - if (e.key == "Enter" && username != "" && password != "") { - login(); - } - }} - /> - {error ? : ""} - + +
e.preventDefault()} className="flex flex-col gap-2"> +

Login

+ + + + + + { + if (e.key === "Enter" && canSubmit) { + login(); + } + }} + /> + + {error && } + + +
);