import { clearProductDraft, saveProductDraft, type ProductDraftData, } from '@/lib/product-draft'; import { router } from '@inertiajs/react'; import { useEffect, useRef } from 'react'; type DraftType = 'create' | 'edit'; export function useProductDraftSave( type: DraftType, data: ProductDraftData, userId?: number, productId?: number, delay = 500, ) { const timeoutRef = useRef | null>(null); const dataRef = useRef(data); dataRef.current = data; const submittedRef = useRef(false); 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) { saveProductDraft(type, dataRef.current, userId, productId); } timeoutRef.current = null; }, delay); return () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } }; }, [data, type, userId, productId, delay]); useEffect(() => { return () => { if (timeoutRef.current) { clearTimeout(timeoutRef.current); } if (submittedRef.current) { clearProductDraft(type, userId, productId); } else { saveProductDraft(type, dataRef.current, userId, productId); } }; }, [type, userId, productId]); }