feat: store logged account
This commit is contained in:
@ -1,3 +1,4 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { Card, CardContent } from "@/components/ui/card";
|
||||
import { Mail, Lock } from "lucide-react";
|
||||
import { Link } from "react-router-dom";
|
||||
@ -7,6 +8,8 @@ import { Button } from "@/components/ui/button";
|
||||
import overlay from "@/assets/overlay.jpg";
|
||||
import { useForm, type SubmitHandler } from "react-hook-form";
|
||||
import { useCallback, useState } from "react";
|
||||
import { loginApi } from "@/api/login";
|
||||
import { useAccountRepo } from "@/repository/account";
|
||||
|
||||
interface LoginForm {
|
||||
email: string;
|
||||
@ -25,6 +28,8 @@ export default function LoginPage() {
|
||||
const [error, setError] = useState("");
|
||||
const [success, setSuccess] = useState("");
|
||||
|
||||
const repo = useAccountRepo();
|
||||
|
||||
const onSubmit: SubmitHandler<LoginForm> = useCallback(
|
||||
async (data) => {
|
||||
console.log({ data });
|
||||
@ -34,36 +39,34 @@ export default function LoginPage() {
|
||||
setSuccess("");
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/v1/login", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
email: data.email,
|
||||
password: data.password,
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
const response = await loginApi({
|
||||
email: data.email,
|
||||
password: data.password,
|
||||
});
|
||||
if (response.status != 200) {
|
||||
const json = await response.json();
|
||||
const text = json.error || "Unexpected error happened";
|
||||
setError(
|
||||
`Failed to create an account. ${
|
||||
text[0].toUpperCase() + text.slice(1)
|
||||
}`
|
||||
);
|
||||
} else {
|
||||
setSuccess("You have successfully logged in");
|
||||
reset();
|
||||
}
|
||||
} catch (err) {
|
||||
|
||||
console.log(response);
|
||||
|
||||
await repo.save({
|
||||
accountId: response.id,
|
||||
label: response.full_name,
|
||||
email: response.email,
|
||||
access: response.access,
|
||||
refresh: response.refresh,
|
||||
});
|
||||
|
||||
setSuccess("You have successfully logged in");
|
||||
reset();
|
||||
} catch (err: any) {
|
||||
console.log(err);
|
||||
setError("Failed to create account. Unexpected error happened");
|
||||
setError(
|
||||
"Failed to create account. " +
|
||||
(err.message ?? "Unexpected error happened")
|
||||
);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
},
|
||||
[reset]
|
||||
[repo, reset]
|
||||
);
|
||||
|
||||
return (
|
||||
|
Reference in New Issue
Block a user