69 lines
1.9 KiB
TypeScript
69 lines
1.9 KiB
TypeScript
import {
|
|
clearRawMaterialDraft,
|
|
saveRawMaterialDraft,
|
|
type RawMaterialDraftData,
|
|
} from '@/lib/raw-material-draft';
|
|
import { router } from '@inertiajs/react';
|
|
import { useEffect, useRef } from 'react';
|
|
|
|
type DraftType = 'create' | 'edit';
|
|
|
|
export function useRawMaterialDraftSave(
|
|
type: DraftType,
|
|
data: RawMaterialDraftData,
|
|
userId?: number,
|
|
rawMaterialId?: number,
|
|
delay = 500,
|
|
) {
|
|
const timeoutRef = useRef<ReturnType<typeof setTimeout> | 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) {
|
|
saveRawMaterialDraft(type, dataRef.current, userId, rawMaterialId);
|
|
}
|
|
timeoutRef.current = null;
|
|
}, delay);
|
|
|
|
return () => {
|
|
if (timeoutRef.current) {
|
|
clearTimeout(timeoutRef.current);
|
|
}
|
|
};
|
|
}, [data, type, userId, rawMaterialId, delay]);
|
|
|
|
useEffect(() => {
|
|
return () => {
|
|
if (timeoutRef.current) {
|
|
clearTimeout(timeoutRef.current);
|
|
}
|
|
if (submittedRef.current) {
|
|
clearRawMaterialDraft(type, userId, rawMaterialId);
|
|
} else {
|
|
saveRawMaterialDraft(type, dataRef.current, userId, rawMaterialId);
|
|
}
|
|
};
|
|
}, [type, userId, rawMaterialId]);
|
|
}
|