From e012b6ff1207b311948d45bf5e1589627f9830db Mon Sep 17 00:00:00 2001 From: Imbus <> Date: Sun, 17 Mar 2024 22:48:38 +0100 Subject: [PATCH] Error checking in register component, redirect to login if success --- frontend/src/API/API.ts | 14 ++++++++++---- frontend/src/Components/Register.tsx | 21 +++++++++++++++++---- 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/frontend/src/API/API.ts b/frontend/src/API/API.ts index 248ad37..9b11dba 100644 --- a/frontend/src/API/API.ts +++ b/frontend/src/API/API.ts @@ -37,13 +37,19 @@ export const api: API = { }); if (!response.ok) { - return { success: false, message: "Failed to register user" }; + return { + success: false, + message: "Failed to register user: " + response.status, + }; } else { - const data = (await response.json()) as User; - return { success: true, data }; + // const data = (await response.json()) as User; // The API does not currently return the user + return { success: true }; } } catch (e) { - return { success: false, message: "Failed to register user" }; + return { + success: false, + message: "Unknown error while registering user", + }; } }, diff --git a/frontend/src/Components/Register.tsx b/frontend/src/Components/Register.tsx index e4a3ba0..9e767ca 100644 --- a/frontend/src/Components/Register.tsx +++ b/frontend/src/Components/Register.tsx @@ -3,14 +3,26 @@ import { NewUser } from "../Types/Users"; import { api } from "../API/API"; import Logo from "../assets/Logo.svg"; import Button from "./Button"; +import { useNavigate } from "react-router-dom"; export default function Register(): JSX.Element { - const [username, setUsername] = useState(""); - const [password, setPassword] = useState(""); + const [username, setUsername] = useState(); + const [password, setPassword] = useState(); + const [errMessage, setErrMessage] = useState(); + + const nav = useNavigate(); const handleRegister = async (): Promise => { - const newUser: NewUser = { userName: username, password }; - await api.registerUser(newUser); // TODO: Handle errors + const newUser: NewUser = { + userName: username ?? "", + password: password ?? "", + }; + const response = await api.registerUser(newUser); + if (response.success) { + nav("/"); // Instantly navigate to the login page + } else { + setErrMessage(response.message ?? "Unknown error"); + } }; return ( @@ -67,6 +79,7 @@ export default function Register(): JSX.Element { }} /> + {errMessage &&

{errMessage}

}