summaryrefslogtreecommitdiff
path: root/src/lib/auth/hooks/useLogin.js
diff options
context:
space:
mode:
authorRafi Zadanly <zadanlyr@gmail.com>2023-03-20 14:33:21 +0700
committerRafi Zadanly <zadanlyr@gmail.com>2023-03-20 14:33:21 +0700
commit833488811b4164d7fbdce9bd70e171f06d62bf8d (patch)
treec781a3ced1f27b8f1c81ed5401fd758d79c1de1c /src/lib/auth/hooks/useLogin.js
parent87e7292941a251f09b5af39d9020896a3bfb0f97 (diff)
login and register
Diffstat (limited to 'src/lib/auth/hooks/useLogin.js')
-rw-r--r--src/lib/auth/hooks/useLogin.js74
1 files changed, 74 insertions, 0 deletions
diff --git a/src/lib/auth/hooks/useLogin.js b/src/lib/auth/hooks/useLogin.js
new file mode 100644
index 00000000..bef36053
--- /dev/null
+++ b/src/lib/auth/hooks/useLogin.js
@@ -0,0 +1,74 @@
+import Link from '@/core/components/elements/Link/Link'
+import { setAuth } from '@/core/utils/auth'
+import { useRouter } from 'next/router'
+import { useRef, useState } from 'react'
+import loginApi from '../api/loginApi'
+
+const useLogin = () => {
+ const router = useRouter()
+ const [isLoading, setIsLoading] = useState(false)
+ const [alert, setAlert] = useState(null)
+ const [isValid, setIsValid] = useState(false)
+
+ const emailRef = useRef(null)
+ const passwordRef = useRef(null)
+
+ const inputVal = () => ({
+ email: emailRef.current.value,
+ password: passwordRef.current.value
+ })
+
+ const handleChangeInput = () => {
+ const { email, password } = inputVal()
+ const isValidInput = email && password
+ setIsValid(isValidInput)
+ }
+
+ const handleSubmit = async (e) => {
+ e.preventDefault()
+ setAlert(null)
+ setIsLoading(true)
+ const { email, password } = inputVal()
+ const login = await loginApi({ email, password })
+ setIsLoading(false)
+
+ if (login.isAuth) {
+ setAuth(login.user)
+ router.push('/')
+ return
+ }
+ switch (login.reason) {
+ case 'NOT_FOUND':
+ setAlert({
+ children: 'Email atau password tidak cocok',
+ type: 'info'
+ })
+ break
+ case 'NOT_ACTIVE':
+ setAlert({
+ children: (
+ <>
+ Email belum diaktivasi,
+ <Link className='text-gray-900' href={`/activate?email=${email}`}>
+ aktivasi sekarang
+ </Link>
+ </>
+ ),
+ type: 'info'
+ })
+ break
+ }
+ }
+
+ return {
+ handleChangeInput,
+ handleSubmit,
+ isLoading,
+ isValid,
+ alert,
+ emailRef,
+ passwordRef
+ }
+}
+
+export default useLogin