import { useContext, useEffect, useState } from "react"; import { Link, useNavigate } from "react-router-dom"; import { loginRequest, registerRequest } from "../api/auth"; import { checkIfUserExists } from "../api/users"; import ErrorMessage from "../components/common/ErrorMessage"; import FormInput from "../components/common/FormInput"; import { AuthContext } from "../context/AuthContext"; import "../styles/pages/Register.css"; export default function Register() { const navigate = useNavigate(); const { login } = useContext(AuthContext); const [name, setName] = useState(""); const [username, setUsername] = useState(""); const [userExists, setUserExists] = useState(false); const [password, setPassword] = useState(""); const [passwordMatches, setPasswordMatches] = useState(true); const [confirm, setConfirm] = useState(""); const [error, setError] = useState(""); const [success, setSuccess] = useState(""); useEffect(() => { checkIfUserExistsHandler(); }, [username]); async function checkIfUserExistsHandler() { setUserExists((await checkIfUserExists(username)).data); } useEffect(() => { setError(userExists ? `Username '${username}' already taken` : ""); }, [userExists]); useEffect(() => { setPasswordMatches(!password || !confirm || password === confirm); }, [password, confirm]); useEffect(() => { setError(passwordMatches ? "" : "Passwords are not matching"); }, [passwordMatches]); const submit = async (e) => { e.preventDefault(); setError(""); setSuccess(""); try { await registerRequest(username, password, name); const data = await loginRequest(username, password); login(data); setSuccess("Account created! Redirecting to the grocery list..."); setTimeout(() => navigate("/"), 2000); } catch (err) { setError(err.response?.data?.message || "Registration failed"); setTimeout(() => setError(""), 1000); } }; return (
Already have an account? Login here