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

UnsavedChangesWarning: Don't return a function from 'mapSelect' #53672

Merged
merged 2 commits into from
Aug 16, 2023
Merged
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
49 changes: 22 additions & 27 deletions packages/editor/src/components/unsaved-changes-warning/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,41 +13,36 @@ import { store as coreStore } from '@wordpress/core-data';
* @return {WPComponent} The component.
*/
export default function UnsavedChangesWarning() {
const isDirty = useSelect( ( select ) => {
return () => {
const { __experimentalGetDirtyEntityRecords } = select( coreStore );
const { __experimentalGetDirtyEntityRecords } = useSelect( coreStore );

useEffect( () => {
/**
* Warns the user if there are unsaved changes before leaving the editor.
*
* @param {Event} event `beforeunload` event.
*
* @return {string | undefined} Warning prompt message, if unsaved changes exist.
*/
const warnIfUnsavedChanges = ( event ) => {
// We need to call the selector directly in the listener to avoid race
// conditions with `BrowserURL` where `componentDidUpdate` gets the
// new value of `isEditedPostDirty` before this component does,
// causing this component to incorrectly think a trashed post is still dirty.
const dirtyEntityRecords = __experimentalGetDirtyEntityRecords();
return dirtyEntityRecords.length > 0;
if ( dirtyEntityRecords.length > 0 ) {
event.returnValue = __(
'You have unsaved changes. If you proceed, they will be lost.'
);
return event.returnValue;
}
};
}, [] );

/**
* Warns the user if there are unsaved changes before leaving the editor.
*
* @param {Event} event `beforeunload` event.
*
* @return {string | undefined} Warning prompt message, if unsaved changes exist.
*/
const warnIfUnsavedChanges = ( event ) => {
// We need to call the selector directly in the listener to avoid race
// conditions with `BrowserURL` where `componentDidUpdate` gets the
// new value of `isEditedPostDirty` before this component does,
// causing this component to incorrectly think a trashed post is still dirty.
if ( isDirty() ) {
event.returnValue = __(
'You have unsaved changes. If you proceed, they will be lost.'
);
return event.returnValue;
}
};

useEffect( () => {
window.addEventListener( 'beforeunload', warnIfUnsavedChanges );

return () => {
window.removeEventListener( 'beforeunload', warnIfUnsavedChanges );
};
}, [] );
}, [ __experimentalGetDirtyEntityRecords ] );

return null;
}