1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
|
"use client";
import toast from "@/common/libs/toast";
import { useLoginStore } from "@/common/stores/useLoginStore"
import { Button, Input, Spinner } from "@nextui-org/react"
import { useMutation } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { useMemo } from "react";
const Form = () => {
const { form, updateForm } = useLoginStore()
const router = useRouter()
const errorMessage = {
401: 'Username atau password tidak sesuai',
404: 'Akun dengan username tersebut tidak ditemukan'
}
const mutation = useMutation({
mutationKey: ['login'],
mutationFn: async (data: typeof form) => await fetch("/api/auth/login", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
}),
onError() {
toast('Mohon maaf terjadi kesalahan')
},
async onSuccess(data) {
if (data.status !== 200) {
return toast(errorMessage[data.status as keyof typeof errorMessage])
}
router.push('/')
},
})
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
updateForm(e.target.name, e.target.value)
}
const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
mutation.mutate(form)
}
const isValid = useMemo(() => {
return form.username && form.password
}, [form])
return (
<form className="grid grid-cols-1 gap-y-4" onSubmit={handleSubmit}>
<Input
isRequired
type="text"
label="Nama Pengguna"
name="username"
onChange={handleInputChange}
autoFocus
/>
<Input
isRequired
type="password"
label="Kata Sandi"
name="password"
onChange={handleInputChange}
/>
<Button
variant="solid"
color="primary"
isDisabled={!isValid || mutation.isPending}
className="mt-2"
type="submit"
>
{mutation.isPending ? <Spinner color="white" size="sm" /> : 'Masuk'}
</Button>
</form>
)
}
export default Form
|