Handling Unsaved Data Warnings
Demonstrate using TanStack Router to alert users about unsaved changes before they navigate away from a page, giving them the option to save changes, discard them, or cancel navigation.
import { useBeforeUnload, usePrompt } from 'react-tanstack-router';
function useWarnAboutUnsavedChanges(unsavedChanges) {
// Warn before reloading the page
useBeforeUnload(unsavedChanges);
// Prompt before navigating away
usePrompt(
'You have unsaved changes. Are you sure you want to leave?',
unsavedChanges
);
}
This custom hook `useWarnAboutUnsavedChanges` utilizes TanStack Router's `useBeforeUnload` and `usePrompt` to warn users about unsaved changes. `useBeforeUnload` prevents the page from reloading, while `usePrompt` displays a confirmation dialog when attempting to navigate away. The hook takes a boolean `unsavedChanges` to activate the warnings only if there are unsaved changes.
function MyComponent() {
const [unsavedChanges, setUnsavedChanges] = useState(false);
// Example usage of the custom hook inside a component
useWarnAboutUnsavedChanges(unsavedChanges);
// Example function to toggle unsaved changes state
const toggleChangesState = () => setUnsavedChanges(!unsavedChanges);
return (
<div>
<h2>Warning about unsaved changes example</h2>
<button onClick={toggleChangesState}>Toggle Unsaved Changes</button>
</div>
);
}
This component `MyComponent` demonstrates the use of the `useWarnAboutUnsavedChanges` hook. It maintains a state `unsavedChanges` to track whether there are unsaved changes. A button is provided to toggle this state, simulating making or reverting changes. The hook is called with the current state, activating the navigation warnings when unsaved changes are present.