2022-03-23 18:34:23 -04:00
|
|
|
import Cookies from "js-cookie"
|
|
|
|
import { useRouter } from "next/router"
|
|
|
|
import { useEffect, useState } from "react"
|
|
|
|
import useSharedState from "./use-shared-state"
|
2022-03-06 19:46:59 -05:00
|
|
|
|
2022-03-21 04:36:31 -04:00
|
|
|
const useSignedIn = () => {
|
2022-03-23 18:42:22 -04:00
|
|
|
const [signedIn, setSignedIn] = useSharedState(
|
|
|
|
"signedIn",
|
|
|
|
typeof window === "undefined" ? false : !!Cookies.get("drift-token")
|
|
|
|
)
|
|
|
|
const token = Cookies.get("drift-token")
|
|
|
|
const router = useRouter()
|
|
|
|
const signin = (token: string) => {
|
|
|
|
setSignedIn(true)
|
|
|
|
Cookies.set("drift-token", token)
|
|
|
|
}
|
2022-03-06 19:46:59 -05:00
|
|
|
|
2022-03-23 18:42:22 -04:00
|
|
|
const signout = () => {
|
|
|
|
setSignedIn(false)
|
|
|
|
Cookies.remove("drift-token")
|
|
|
|
router.push("/")
|
|
|
|
}
|
2022-03-23 15:36:29 -04:00
|
|
|
|
2022-03-23 18:42:22 -04:00
|
|
|
useEffect(() => {
|
|
|
|
if (token) {
|
|
|
|
setSignedIn(true)
|
|
|
|
} else {
|
|
|
|
setSignedIn(false)
|
|
|
|
}
|
|
|
|
}, [setSignedIn, token])
|
2022-03-06 19:46:59 -05:00
|
|
|
|
2022-03-23 18:42:22 -04:00
|
|
|
return { signedIn, signin, token, signout }
|
2022-03-06 19:46:59 -05:00
|
|
|
}
|
|
|
|
|
2022-03-23 18:34:23 -04:00
|
|
|
export default useSignedIn
|