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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
import { useEffect, useMemo, useState } from 'react';
import { favoritesService } from '@/features/offices/services/favoritesService';
import { useAuthSession } from '@/providers/AuthProvider';
import { getErrorMessage } from '@/shared/lib/errors/getErrorMessage';
export function useFavoriteOffices() {
const { user } = useAuthSession();
const [favoriteOfficeIds, setFavoriteOfficeIds] = useState<string[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [pendingOfficeId, setPendingOfficeId] = useState<string | null>(null);
const loadFavorites = async () => {
if (!user?.uid) {
setFavoriteOfficeIds([]);
setLoading(false);
return;
}
try {
setError(null);
setLoading(true);
const data = await favoritesService.getByUserId(user.uid);
setFavoriteOfficeIds(data);
} catch (err) {
setError(getErrorMessage(err, 'No se pudieron cargar los favoritos'));
} finally {
setLoading(false);
}
};
useEffect(() => {
loadFavorites();
}, [user?.uid]);
const favoriteOfficeIdsSet = useMemo(
() => new Set(favoriteOfficeIds),
[favoriteOfficeIds]
);
const toggleFavorite = async (officeId: string) => {
if (!user?.uid) {
setError('Debes iniciar sesión para usar favoritos');
return;
}
try {
setError(null);
setPendingOfficeId(officeId);
if (favoriteOfficeIdsSet.has(officeId)) {
await favoritesService.remove(user.uid, officeId);
setFavoriteOfficeIds((current) => current.filter((id) => id !== officeId));
} else {
await favoritesService.add(user.uid, officeId);
setFavoriteOfficeIds((current) => [...current, officeId]);
}
} catch (err) {
setError(getErrorMessage(err, 'No se pudo actualizar el favorito'));
} finally {
setPendingOfficeId(null);
}
};
return {
favoriteOfficeIds,
favoriteOfficeIdsSet,
isLoadingFavorites: loading,
favoritesError: error,
pendingOfficeId,
toggleFavorite,
reloadFavorites: loadFavorites,
};
}
|