diff --git a/src/hooks/useDirectory.js b/src/hooks/useDirectory.js index 7d18a554..b27dc63a 100644 --- a/src/hooks/useDirectory.js +++ b/src/hooks/useDirectory.js @@ -2,35 +2,43 @@ import { useEffect, useState } from "react"; import { DirectoryRepository } from "../repositories/DirectoryRepository"; import { cacheData, getCachedData } from "../slices/apiDataManager"; -export const useDirectory = () => { +export const useDirectory = (isActive) => { const [contacts, setContacts] = useState([]); const [loading, setLoading] = useState(false); - const [error, setError] = useState(); + const [error, setError] = useState(null); - const fetch = async () => { - const cache_contacts = getCachedData("contacts"); - if (!cache_contacts) { - setLoading(true); - try { - const response = await DirectoryRepository.GetContacts(); - setContacts(response.data); - cacheData("contacts", response.data); - setLoading(false); - } catch (error) { - setError(error); - setLoading(false); - } - } else { - setContacts(cache_contacts); + const fetch = async (activeParam = isActive) => { + setLoading(true); + try { + const response = await DirectoryRepository.GetContacts(activeParam); + setContacts(response.data); + cacheData("contacts", { data: response.data, isActive: activeParam }); + } catch (error) { + setError(error); + } finally { + setLoading(false); } }; - useState(() => { - fetch(); - }, []); - return { contacts, loading, error }; + useEffect(() => { + const cachedContacts = getCachedData("contacts"); + if (!cachedContacts?.data || cachedContacts.isActive !== isActive) { + fetch(isActive); + } else { + setContacts(cachedContacts.data); + } + }, [isActive]); + + return { + contacts, + loading, + error, + refetch: fetch, + }; }; + + export const useBuckets = () => { const [buckets, setBuckets] = useState([]); const [loading, setLoading] = useState(false);