import { useEffect, useState } from 'react'; import { ACTION_FAILED_TEXT, FEED_SEARCH_DEBOUNCE_MS, } from '../../service/ai-shopping-feeds/ai-shopping-feeds.constants'; import type { IFeedGroups, IFeedRules, } from '../../service/ai-shopping-feeds/ai-shopping-feeds.interface'; import { getFeedGroups } from '../../service/ai-shopping-feeds/ai-shopping-feeds.service'; import { selectionRules } from './rules'; /** The store's brands and categories under the draft rules. */ export interface FeedGroupsState { /** Null before the first answer. */ groups: IFeedGroups | null; isLoading: boolean; error: string | null; } /** * Read the store's brands and categories, with their products listed under * the draft rules, again a moment after a rule or a save changes; an answer * to older rules is dropped. * * @param {IFeedRules} draft - The rules as edited. * @param {string | null} savedAt - When the rules were last saved. * @return {FeedGroupsState} The brands and categories. */ export function useFeedGroups( draft: IFeedRules, savedAt: string | null ): FeedGroupsState { const [groups, setGroups] = useState(null); const [isLoading, setLoading] = useState(false); const [error, setError] = useState(null); const selectionJson = JSON.stringify(selectionRules(draft)); useEffect(() => { let isCurrent = true; const timer = setTimeout(() => { setLoading(true); getFeedGroups(JSON.parse(selectionJson)) .then(answer => { if (!isCurrent) return; setGroups(answer); setError(null); }) .catch(() => { if (isCurrent) setError(ACTION_FAILED_TEXT); }) .finally(() => { if (isCurrent) setLoading(false); }); }, FEED_SEARCH_DEBOUNCE_MS); return () => { isCurrent = false; clearTimeout(timer); }; }, [selectionJson, savedAt]); return { groups, isLoading, error }; }