import { useBlocker, useFetcher } from "react-router";
import { useState, useEffect } from "react";
export default function AutoSaveForm() {
const fetcher = useFetcher();
const [formData, setFormData] = useState("");
const [lastSaved, setLastSaved] = useState(formData);
const hasUnsavedChanges = formData !== lastSaved;
// Auto-save every 30 seconds
useEffect(() => {
if (hasUnsavedChanges) {
const timer = setTimeout(() => {
fetcher.submit({ data: formData }, { method: "post" });
}, 30000);
return () => clearTimeout(timer);
}
}, [formData, hasUnsavedChanges]);
// Update lastSaved when auto-save completes
useEffect(() => {
if (fetcher.state === "idle" && fetcher.data?.success) {
setLastSaved(formData);
}
}, [fetcher.state, fetcher.data, formData]);
const blocker = useBlocker(
({ currentLocation, nextLocation }) =>
hasUnsavedChanges && currentLocation.pathname !== nextLocation.pathname
);
return (
<div>
<textarea
value={formData}
onChange={(e) => setFormData(e.target.value)}
/>
{hasUnsavedChanges && <p>Unsaved changes</p>}
{fetcher.state === "submitting" && <p>Saving...</p>}
</div>
);
}