all repos — caroster @ ba1f0945c383630d88192de37465dc72ebca0328

[Octree] Group carpool to your event https://caroster.io

frontend/hooks/useProfile.ts (view raw)

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