dstpabuaran.com/resources/js/hooks/use-draft-save.ts
Yoga Pangestu d91ec8869e refactor: replace tooltip buttons with row actions component in supplier and role columns
feat: implement delete confirmation dialog component for better UX

refactor: update supplier and role index pages to utilize new form dialog and delete confirm dialog components

feat: add reusable form dialog component for creating and editing entities

feat: introduce filter popover component for enhanced filtering options in data tables

feat: create image preview button component for displaying images with modal preview

feat: add page header component for consistent page layout

feat: implement row actions component for handling actions on table rows

feat: add status badge component for displaying entity statuses

feat: create toggle status component for easily toggling entity states

feat: implement draft save hook for auto-saving form data

feat: add server table hook for managing server-side pagination and filtering

feat: create utility functions for formatting dates and numbers

feat: add constants for month names and measurement units
2026-08-02 23:40:12 +07:00

77 lines
1.9 KiB
TypeScript

import { router } from '@inertiajs/react';
import { useEffect, useRef } from 'react';
import type { DraftStore, DraftType } from '@/lib/draft-store';
type UseDraftSaveOptions<D> = {
type: DraftType;
data: D;
userId?: number;
extraId?: number;
delay?: number;
store: Pick<DraftStore<D>, 'save' | 'clear'>;
};
export function useDraftSave<D>({
type,
data,
userId,
extraId,
delay = 500,
store,
}: UseDraftSaveOptions<D>) {
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) {
store.save(type, dataRef.current, userId, extraId);
}
timeoutRef.current = null;
}, delay);
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, [data, type, userId, extraId, delay, store]);
useEffect(() => {
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
if (submittedRef.current) {
store.clear(type, userId, extraId);
} else {
store.save(type, dataRef.current, userId, extraId);
}
};
}, [type, userId, extraId, store]);
}