CoastalCommitsPastes/client/lib/hooks/use-user-data.ts

44 lines
948 B
TypeScript
Raw Normal View History

2022-03-29 03:19:33 -04:00
import { User } from "@lib/types"
import Cookies from "js-cookie"
2022-11-09 21:38:05 -05:00
import { useRouter } from "next/navigation"
import { useEffect, useState } from "react"
const useUserData = () => {
2022-03-29 03:19:33 -04:00
const [authToken, setAuthToken] = useState<string>(
Cookies.get("drift-token") || ""
)
const [user, setUser] = useState<User>()
const router = useRouter()
useEffect(() => {
const token = Cookies.get("drift-token")
if (token) {
setAuthToken(token)
}
}, [setAuthToken])
2022-03-29 03:19:33 -04:00
useEffect(() => {
if (authToken) {
const fetchUser = async () => {
const response = await fetch(`/server-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 {
Cookies.remove("drift-token")
setAuthToken("")
router.push("/")
}
}
fetchUser()
}
}, [authToken, router])
2022-03-29 03:19:33 -04:00
return user
}
2022-03-29 03:19:33 -04:00
export default useUserData