frontend/hooks/useProfile.ts (view raw)
1import {useEffect, useState} from 'react';
2import {ProfileDocument, UsersPermissionsUser} from '../generated/graphql';
3import {initializeApollo} from '../lib/apolloClient';
4import {useSession} from 'next-auth/react';
5
6const useProfile = () => {
7 const session = useSession();
8 const [isReady, setIsReady] = useState(false);
9 const [profile, setProfile] = useState<UsersPermissionsUser | null>(null);
10 const [userId, setUserId] = useState<string | null>(null);
11
12 const fetchProfile = async () => {
13 const jwt = session?.data?.token?.jwt;
14 const apolloClient = initializeApollo('', jwt);
15
16 try {
17 const {data} = await apolloClient.query({
18 query: ProfileDocument,
19 });
20 const fetchedProfile = data?.me?.profile;
21 setProfile(fetchedProfile);
22 setUserId(data?.me?.id);
23 } catch (error) {
24 console.error(error);
25 } finally {
26 setIsReady(true);
27 }
28 };
29
30 useEffect(() => {
31 if (session.status === 'authenticated') fetchProfile();
32 else if (session.status === 'unauthenticated') setIsReady(true);
33 }, [session]);
34
35 return {
36 profile,
37 userId,
38 connected: session.status === 'authenticated',
39 isReady,
40 };
41};
42
43export default useProfile;