| 1 |
/** |
| 2 |
* Custom hook for auto-save functionality |
| 3 |
*/ |
| 4 |
|
| 5 |
import { useState, useCallback, useRef } from "react"; |
| 6 |
|
| 7 |
interface UseAutoSaveOptions { |
| 8 |
delay?: number; |
| 9 |
onSave?: () => void; |
| 10 |
} |
| 11 |
|
| 12 |
export const useAutoSave = (options: UseAutoSaveOptions = {}) => { |
| 13 |
const { delay = 1000, onSave } = options; |
| 14 |
const [isAutoSaving, setIsAutoSaving] = useState(false); |
| 15 |
const [lastSaved, setLastSaved] = useState<Date | null>(null); |
| 16 |
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null); |
| 17 |
|
| 18 |
const autoSave = useCallback(() => { |
| 19 |
if (timeoutRef.current) { |
| 20 |
clearTimeout(timeoutRef.current); |
| 21 |
} |
| 22 |
|
| 23 |
setIsAutoSaving(true); |
| 24 |
|
| 25 |
timeoutRef.current = setTimeout(() => { |
| 26 |
if (onSave) { |
| 27 |
onSave(); |
| 28 |
} |
| 29 |
setLastSaved(new Date()); |
| 30 |
setIsAutoSaving(false); |
| 31 |
}, delay); |
| 32 |
}, [delay, onSave]); |
| 33 |
|
| 34 |
return { |
| 35 |
isAutoSaving, |
| 36 |
lastSaved, |
| 37 |
autoSave, |
| 38 |
}; |
| 39 |
}; |
| 40 |
|