diff --git a/packages/edit-widgets/src/components/layout/unsaved-changes-warning.js b/packages/edit-widgets/src/components/layout/unsaved-changes-warning.js index 15803c7fc27f4..aec1250ad9710 100644 --- a/packages/edit-widgets/src/components/layout/unsaved-changes-warning.js +++ b/packages/edit-widgets/src/components/layout/unsaved-changes-warning.js @@ -5,6 +5,11 @@ import { __ } from '@wordpress/i18n'; import { useEffect } from '@wordpress/element'; import { useSelect } from '@wordpress/data'; +/** + * Internal dependencies + */ +import { store as editWidgetsStore } from '../../store'; + /** * Warns the user if there are unsaved changes before leaving the editor. * @@ -14,12 +19,11 @@ import { useSelect } from '@wordpress/data'; * @return {WPComponent} The component. */ export default function UnsavedChangesWarning() { - const getIsDirty = useSelect( ( select ) => { - return () => { - const { __experimentalGetDirtyEntityRecords } = select( 'core' ); - const dirtyEntityRecords = __experimentalGetDirtyEntityRecords(); - return dirtyEntityRecords.length > 0; - }; + const isDirty = useSelect( ( select ) => { + const { getEditedWidgetAreas } = select( editWidgetsStore ); + const editedWidgetAreas = getEditedWidgetAreas(); + + return editedWidgetAreas?.length > 0; }, [] ); useEffect( () => { @@ -31,11 +35,7 @@ export default function UnsavedChangesWarning() { * @return {?string} 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 ( getIsDirty() ) { + if ( isDirty ) { event.returnValue = __( 'You have unsaved changes. If you proceed, they will be lost.' ); @@ -48,7 +48,7 @@ export default function UnsavedChangesWarning() { return () => { window.removeEventListener( 'beforeunload', warnIfUnsavedChanges ); }; - }, [ getIsDirty ] ); + }, [ isDirty ] ); return null; }