2022-03-29 03:19:33 -04:00
|
|
|
import { User } from "@lib/types"
|
2022-11-09 22:46:12 -05:00
|
|
|
import { deleteCookie, getCookie } from "cookies-next"
|
2022-11-09 21:38:05 -05:00
|
|
|
import { useRouter } from "next/navigation"
|
|
|
|
import { useEffect, useState } from "react"
|
2022-03-28 15:13:22 -04:00
|
|
|
|
|
|
|
const useUserData = () => {
|
2022-11-09 22:46:12 -05:00
|
|
|
const cookie = getCookie("drift-token")
|
2022-03-29 03:19:33 -04:00
|
|
|
const [authToken, setAuthToken] = useState<string>(
|
2022-11-09 22:46:12 -05:00
|
|
|
cookie ? String(cookie) : ""
|
2022-03-29 03:19:33 -04:00
|
|
|
)
|
|
|
|
const [user, setUser] = useState<User>()
|
|
|
|
const router = useRouter()
|
|
|
|
useEffect(() => {
|
2022-11-09 22:46:12 -05:00
|
|
|
const token = getCookie("drift-token")
|
2022-03-29 03:19:33 -04:00
|
|
|
if (token) {
|
2022-11-09 22:46:12 -05:00
|
|
|
setAuthToken(String(token))
|
2022-03-29 03:19:33 -04:00
|
|
|
}
|
|
|
|
}, [setAuthToken])
|
2022-03-28 15:13:22 -04:00
|
|
|
|
2022-03-29 03:19:33 -04:00
|
|
|
useEffect(() => {
|
|
|
|
if (authToken) {
|
|
|
|
const fetchUser = async () => {
|
2022-11-09 22:46:12 -05:00
|
|
|
const response = await fetch(`/api/user/self`, {
|
2022-03-29 03:19:33 -04:00
|
|
|
headers: {
|
|
|
|
Authorization: `Bearer ${authToken}`
|
|
|
|
}
|
|
|
|
})
|
|
|
|
if (response.ok) {
|
|
|
|
const user = await response.json()
|
|
|
|
setUser(user)
|
|
|
|
} else {
|
2022-11-09 22:46:12 -05:00
|
|
|
deleteCookie("drift-token")
|
2022-03-29 03:19:33 -04:00
|
|
|
setAuthToken("")
|
|
|
|
router.push("/")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
fetchUser()
|
|
|
|
}
|
|
|
|
}, [authToken, router])
|
2022-03-28 15:13:22 -04:00
|
|
|
|
2022-03-29 03:19:33 -04:00
|
|
|
return user
|
2022-03-28 15:13:22 -04:00
|
|
|
}
|
|
|
|
|
2022-03-29 03:19:33 -04:00
|
|
|
export default useUserData
|