diff --git a/frontend/src/hooks/api/useLogin.ts b/frontend/src/hooks/api/useLogin.ts new file mode 100644 index 0000000..54ab842 --- /dev/null +++ b/frontend/src/hooks/api/useLogin.ts @@ -0,0 +1,13 @@ +import { useMutation } from '@tanstack/react-query'; +import { login } from '../../api/auth.api'; +import { setToken } from '../../utils/credentials'; + +export function useLogin() { + return useMutation({ + mutationFn: async ({ name, password }: { name: string; password: string }) => { + const token = await login(name, password); + setToken(token); + return token; + }, + }); +} diff --git a/frontend/src/pages/Login/Login.tsx b/frontend/src/pages/Login/Login.tsx index 02acbc5..1cb25d4 100644 --- a/frontend/src/pages/Login/Login.tsx +++ b/frontend/src/pages/Login/Login.tsx @@ -1,50 +1,87 @@ import { useState } from 'react'; import { useNavigate } from 'react-router'; -import { login } from '../../api/auth.api'; +import { useLogin } from '../../hooks/api/useLogin'; import { Input } from '../../components/ui/input'; import { Button } from '../../components/ui/button'; -import { setToken } from '../../utils/credentials'; +import { + Card, + CardContent, + CardDescription, + CardFooter, + CardHeader, + CardTitle, +} from '../../components/ui/card'; +import { LogIn, TriangleAlert } from 'lucide-react'; +import { Spinner } from '../../components/ui/spinner'; const Login = () => { const [name, setName] = useState(''); const [password, setPassword] = useState(''); - const [error, setError] = useState(null); const navigate = useNavigate(); + const { mutate, isPending, error: mutationError } = useLogin(); const handleSubmit = async (e: React.FormEvent) => { e.preventDefault(); - setError(null); - try { - const token = await login(name, password); - setToken(token); - navigate('/'); - } catch { - setError('Invalid credentials'); - } + mutate( + { name, password }, + { + onSuccess: () => { + navigate('/'); + }, + } + ); }; return (
-

Sign in

-
-
- - setName(e.target.value)} required /> -
-
- - setPassword(e.target.value)} - required - /> -
- {error &&

{error}

} -
- -
-
+ + + Sign in + Enter your credentials to access your account + + +
+
+ + setName(e.target.value)} + required + /> +
+
+ + setPassword(e.target.value)} + required + /> +
+ {mutationError && ( +
+ +

Invalid credentials

+
+ )} +
+
+ + + +
); };