import { router } from '@inertiajs/react'; import { useEffect, useRef } from 'react'; import { clearRestockDraft, saveRestockDraft } from '@/lib/restock-draft'; import type {RestockDraftData} from '@/lib/restock-draft'; type DraftType = 'create' | 'edit'; export function useRestockDraftSave( type: DraftType, data: RestockDraftData, userId?: number, delay = 500, ) { const timeoutRef = useRef | null>(null); const dataRef = useRef(data); const submittedRef = useRef(false); useEffect(() => { dataRef.current = data; }, [data]); useEffect(() => { const offBefore = router.on('before', (event) => { if (event.detail.visit.method !== 'get') { submittedRef.current = true; } }); const offError = router.on('error', () => { submittedRef.current = false; }); return () => { offBefore(); offError(); }; }, []); useEffect(() => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } timeoutRef.current = setTimeout(() => { if (!submittedRef.current) { saveRestockDraft(type, dataRef.current, userId); } timeoutRef.current = null; }, delay); return () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } }; }, [data, type, userId, delay]); useEffect(() => { return () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } if (submittedRef.current) { clearRestockDraft(type, userId); } else { saveRestockDraft(type, dataRef.current, userId); } }; }, [type, userId]); }