11import React from 'react' ;
2+ import ReactDOM from 'react-dom' ;
23import PropTypes from 'prop-types' ;
34import cx from 'classnames' ;
45import assign from 'object-assign' ;
@@ -9,6 +10,15 @@ import SubMenu from './SubMenu';
910import { hideMenu } from './actions' ;
1011import { cssClasses , callIfExists , store } from './helpers' ;
1112
13+ /* This is a backward-compatible shim for React < 18 */
14+ function flushSync ( callback ) {
15+ if ( ReactDOM . flushSync ) {
16+ ReactDOM . flushSync ( callback ) ;
17+ } else {
18+ callback ( ) ;
19+ }
20+ }
21+
1222export default class ContextMenu extends AbstractMenu {
1323 static propTypes = {
1424 id : PropTypes . string . isRequired ,
@@ -124,7 +134,11 @@ export default class ContextMenu extends AbstractMenu {
124134 handleHide = ( e ) => {
125135 if ( this . state . isVisible && ( ! e . detail || ! e . detail . id || e . detail . id === this . props . id ) ) {
126136 this . unregisterHandlers ( ) ;
127- this . setState ( { isVisible : false , selectedItem : null , forceSubMenuOpen : false } ) ;
137+ flushSync ( ( ) => {
138+ /* We rely on being able to read this state change in handleShow,
139+ * so let's force a synchronous update in React 18. */
140+ this . setState ( { isVisible : false , selectedItem : null , forceSubMenuOpen : false } ) ;
141+ } ) ;
128142 callIfExists ( this . props . onHide , e ) ;
129143 }
130144 } ;
0 commit comments