import { FiltersMap, OptionalFiltersMap } from '@wix/bex-core'; import { useWixPatternsContainer } from '@wix/bex-core/react'; import { useEffect, useRef, useState } from 'react'; import { KanbanState, KanbanStateBaseParams } from '../state/KanbanState'; export const useKanban = ( params: KanbanStateBaseParams, ): KanbanState => { const container = useWixPatternsContainer(); if (!container) { throw new Error('useKanban must be used within a WixPatternsContainer'); } const [currentKanbanState, setCurrentKanbanState] = useState< KanbanState >( () => new KanbanState({ ...params, container, }), ); const previousKanbanIdRef = useRef(params.kanbanId); const stateCleanupFunctionRef = useRef<(() => void) | null>(null); useEffect(() => { const hasKanbanIdChanged = previousKanbanIdRef.current !== params.kanbanId; if (hasKanbanIdChanged) { const recreateKanbanStateForNewId = async () => { const cleanupPreviousState = stateCleanupFunctionRef.current; if (cleanupPreviousState) { cleanupPreviousState(); stateCleanupFunctionRef.current = null; } const newKanbanState = new KanbanState({ ...params, container, }); const cleanupFunction = await newKanbanState.init(); stateCleanupFunctionRef.current = cleanupFunction; setCurrentKanbanState(newKanbanState); previousKanbanIdRef.current = params.kanbanId; }; recreateKanbanStateForNewId(); } }, [params.kanbanId, container]); useEffect(() => { const needsInitialization = !stateCleanupFunctionRef.current && previousKanbanIdRef.current === params.kanbanId; if (needsInitialization) { currentKanbanState.init().then((cleanupFunction) => { const isStillCurrentState = previousKanbanIdRef.current === params.kanbanId; if (isStillCurrentState) { stateCleanupFunctionRef.current = cleanupFunction; } else { cleanupFunction?.(); } }); } }, [currentKanbanState, params.kanbanId]); useEffect(() => { return () => { const cleanupCurrentState = stateCleanupFunctionRef.current; if (cleanupCurrentState) { cleanupCurrentState(); } }; }, []); return currentKanbanState; };