import { useEffect, useRef } from 'react'; /** * Re-run a page's data fetch whenever the Reco copilot finishes a write-tool * turn. The copilot panel dispatches a global ``copilot:data-changed`` window * event after actions such as a catalog content check, a scan, or a generation, * and WordPress has no route loaders to revalidate, so each page listens for the * event and re-fetches its own primary data. * * The latest ``onChange`` is kept in a ref so the listener is registered once * and callers never have to memoize their callback to avoid re-subscribing. * * @param onChange {() => void} Called every time ``copilot:data-changed`` fires. * @return {void} */ export function useCopilotDataChanged(onChange: () => void): void { const onChangeRef = useRef<() => void>(onChange); onChangeRef.current = onChange; useEffect(() => { const handleDataChanged = (): void => { onChangeRef.current(); }; window.addEventListener('copilot:data-changed', handleDataChanged); return () => { window.removeEventListener('copilot:data-changed', handleDataChanged); }; }, []); }