summaryrefslogtreecommitdiffstats
path: root/src/features/profile/hooks/useProfile.ts
blob: 82068f45a1944a5e9d8c11629fcebb6b2f4679be (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// src/features/profile/hooks/useProfile.ts

import { useEffect, useState } from 'react';
import { useAuthSession } from '@/providers/AuthProvider';
import { profileService } from '@/features/profile/services/profileService';
import { UserProfile } from '@/features/profile/types';

export function useProfile() {
  const { user } = useAuthSession();

  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const loadProfile = async () => {
    if (!user?.uid) {
      setProfile(null);
      setLoading(false);
      return;
    }

    try {
      setError(null);
      setLoading(true);

      const data = await profileService.getMyProfile(user.uid);
      setProfile(data);
    } catch (err: any) {
      setError(err?.message ?? 'No se pudo cargar el perfil');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadProfile();
  }, [user?.uid]);

  return {
    profile,
    loading,
    error,
    reload: loadProfile,
  };
}