diff --git a/daily-thought-frontend/src/hooks/useUser.ts b/daily-thought-frontend/src/hooks/useUser.ts new file mode 100644 index 0000000000000000000000000000000000000000..7e7d303e6b196c960d92f0c1c80ab2c213a0f5cc --- /dev/null +++ b/daily-thought-frontend/src/hooks/useUser.ts @@ -0,0 +1,30 @@ +import { User } from "@/types/user" +import Router from "next/router" +import { useState, useEffect } from "react" + +export const useUser = () => { + const [user, setUser] = useState<undefined | User>(undefined) + + const fetchUser = async () => { + const endpoint = `${process.env.NEXT_PUBLIC_USER_SERVICE_URL}api/user/${sessionStorage.getItem('username')}` + const response = await fetch(endpoint) + return await response.json() + + } + + useEffect(() => { + if(sessionStorage.length < 2){ + Router.push("/") + } + }) + + useEffect(() => { + if(!user){ + fetchUser().then(res => { + const {_id, username, email, profile, firstName, lastName } = res + setUser({id: _id, email, username, profile, firstName, lastName}) + }) + } + }) + return user +} \ No newline at end of file