Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add useWarnOnPageUnload hook #1676

Merged
merged 1 commit into from
Aug 22, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 62 additions & 0 deletions src/hooks/test/use-warn-on-page-unload-test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { mount } from 'enzyme';
import { useState } from 'preact/hooks';

import { useWarnOnPageUnload } from '../use-warn-on-page-unload';

describe('useWarnOnPageUnload', () => {
let fakeWindow;
const FakeComponent = () => {
const [isUnsaved, setUnsaved] = useState(true);

useWarnOnPageUnload(isUnsaved, fakeWindow);

return (
<button type="button" onClick={() => setUnsaved(false)}>
Set not unsaved
</button>
);
};
const createComponent = () => mount(<FakeComponent />);

const waitForBeforeUnloadEvent = () => {
const promise = new Promise(resolve =>
fakeWindow.addEventListener('beforeunload', resolve),
);
fakeWindow.dispatchEvent(new Event('beforeunload', { cancelable: true }));

return promise;
};

beforeEach(() => {
fakeWindow = new EventTarget();
});

it('registers event listener when unsaved data is true', async () => {
createComponent();

const event = await waitForBeforeUnloadEvent();

assert.isTrue(event.defaultPrevented);
assert.equal(event.returnValue, '');
});

it('unregisters event listener when unsaved data is false', async () => {
const wrapper = createComponent();

wrapper.find('button').simulate('click');
wrapper.update();

const event = await waitForBeforeUnloadEvent();

assert.isFalse(event.defaultPrevented);
});

it('unregisters event listener when component is unmounted', async () => {
const wrapper = createComponent();
wrapper.unmount();

const event = await waitForBeforeUnloadEvent();

assert.isFalse(event.defaultPrevented);
});
});
29 changes: 29 additions & 0 deletions src/hooks/use-warn-on-page-unload.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { useEffect } from 'preact/hooks';

const noop = () => {};

/**
* Registers an event listener to window's 'beforeunload' if `hasUnsavedData` is true.
* It also unregisters the event if `hasUnsavedData` is false or the component is unmounted.
*
* This event listener makes the browser warn the user about potential unsaved changes,
* and gives the user the opportunity to cancel the page unload if desired.
*
* @link https://developer.mozilla.org/en-US/docs/Web/API/Window/beforeunload_event
*/
export function useWarnOnPageUnload(hasUnsavedData: boolean, window_ = window) {
useEffect(() => {
if (!hasUnsavedData) {
return noop;
}

const listener = (e: BeforeUnloadEvent) => {
e.preventDefault();
e.returnValue = '';
};

window_.addEventListener('beforeunload', listener);

return () => window_.removeEventListener('beforeunload', listener);
}, [hasUnsavedData, window_]);
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export { useStableCallback } from './hooks/use-stable-callback';
export { useSyncedRef } from './hooks/use-synced-ref';
export { useToastMessages } from './hooks/use-toast-messages';
export { useValidateOnSubmit } from './hooks/use-validate-on-submit';
export { useWarnOnPageUnload } from './hooks/use-warn-on-page-unload';
export type {
ToastMessagesState,
ToastMessageData,
Expand Down