diff --git a/projects/packages/jetpack-mu-wpcom/changelog/fix-uselocation-exception b/projects/packages/jetpack-mu-wpcom/changelog/fix-uselocation-exception new file mode 100644 index 0000000000000..fc95eb7085776 --- /dev/null +++ b/projects/packages/jetpack-mu-wpcom/changelog/fix-uselocation-exception @@ -0,0 +1,4 @@ +Significance: patch +Type: fixed + +wpcom-block-editor-nux: avoid using useLocation which now throws exception outside Site Editor in Gutenberg 19.9.0 diff --git a/projects/packages/jetpack-mu-wpcom/src/common/hooks/use-canvas-mode.ts b/projects/packages/jetpack-mu-wpcom/src/common/hooks/use-canvas-mode.ts index fba0a4cbdf2c7..d4c1332de6386 100644 --- a/projects/packages/jetpack-mu-wpcom/src/common/hooks/use-canvas-mode.ts +++ b/projects/packages/jetpack-mu-wpcom/src/common/hooks/use-canvas-mode.ts @@ -1,20 +1,25 @@ -import { useSelect } from '@wordpress/data'; -import useLocation from './use-location'; +import { subscribe, useSelect } from '@wordpress/data'; +import { useEffect, useState } from 'react'; const useCanvasMode = () => { - const location = useLocation(); + const [ canvasMode, setCanvasMode ] = useState< string | null >( null ); + const isSiteEditor = useSelect( select => !! select( 'core/edit-site' ), [] ); - return useSelect( - select => { - // The canvas mode is limited to the site editor. - if ( ! select( 'core/edit-site' ) ) { - return null; - } + useEffect( () => { + // The canvas mode is limited to the site editor. + if ( ! isSiteEditor ) { + return; + } - return new URLSearchParams( location?.search ).get( 'canvas' ) || 'view'; - }, - [ location?.search ] - ); + const unsubscribe = subscribe( () => { + const mode = new URLSearchParams( window.location?.search ).get( 'canvas' ) || 'view'; + setCanvasMode( mode ); + } ); + + return () => unsubscribe(); + }, [ isSiteEditor ] ); + + return canvasMode; }; export default useCanvasMode;