- Added RawMaterialController and RawMaterialVariantController for managing raw materials and their variants. - Introduced RawMaterialRequest and RawMaterialVariantRequest for validation. - Implemented RawMaterialService and RawMaterialVariantService for business logic. - Created hooks for saving drafts of raw materials. - Developed UI components for creating, editing, and listing raw materials and variants.
60 lines
1.7 KiB
TypeScript
60 lines
1.7 KiB
TypeScript
import { useEffect, useRef } from 'react';
|
|
import { router } from '@inertiajs/react';
|
|
import {
|
|
saveRawMaterialDraft,
|
|
clearRawMaterialDraft,
|
|
type RawMaterialDraftData,
|
|
} from '@/lib/raw-material-draft';
|
|
|
|
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(() => {
|
|
return router.on('before', () => {
|
|
submittedRef.current = true;
|
|
});
|
|
}, []);
|
|
|
|
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]);
|
|
}
|