diff --git a/packages/core-data/src/entity-provider.js b/packages/core-data/src/entity-provider.js index 2c5d3d7d8001b..0d97ea5161dd3 100644 --- a/packages/core-data/src/entity-provider.js +++ b/packages/core-data/src/entity-provider.js @@ -1,7 +1,12 @@ /** * WordPress dependencies */ -import { createContext, useContext, useCallback } from '@wordpress/element'; +import { + createContext, + useContext, + useCallback, + useMemo, +} from '@wordpress/element'; import { useSelect, useDispatch } from '@wordpress/data'; import { parse, __unstableSerializeAndClean } from '@wordpress/blocks'; @@ -150,7 +155,7 @@ const parsedBlocksCache = new WeakMap(); export function useEntityBlockEditor( kind, name, { id: _id } = {} ) { const providerId = useEntityId( kind, name ); const id = _id ?? providerId; - const { blocks, meta } = useSelect( + const { content, editedBlocks, meta, entityRecord } = useSelect( ( select ) => { if ( ! id ) { return {}; @@ -158,29 +163,11 @@ export function useEntityBlockEditor( kind, name, { id: _id } = {} ) { const { getEditedEntityRecord, getEntityRecord } = select( STORE_NAME ); const editedRecord = getEditedEntityRecord( kind, name, id ); - - let editedBlocks = editedRecord.blocks; - - if ( ! editedBlocks ) { - if ( - editedRecord.content && - typeof editedRecord.content !== 'function' - ) { - // Attach the cache to the original record. - const entityRecord = getEntityRecord( kind, name, id ); - editedBlocks = parsedBlocksCache.get( entityRecord ); - if ( ! editedBlocks ) { - editedBlocks = parse( editedRecord.content ); - parsedBlocksCache.set( entityRecord, editedBlocks ); - } - } else { - editedBlocks = EMPTY_ARRAY; - } - } - return { - blocks: editedBlocks, + editedBlocks: editedRecord.blocks, + content: editedRecord.content, meta: editedRecord.meta, + entityRecord: getEntityRecord( kind, name, id ), }; }, [ kind, name, id ] @@ -188,6 +175,29 @@ export function useEntityBlockEditor( kind, name, { id: _id } = {} ) { const { __unstableCreateUndoLevel, editEntityRecord } = useDispatch( STORE_NAME ); + const blocks = useMemo( () => { + if ( ! id ) { + return undefined; + } + + if ( editedBlocks ) { + return editedBlocks; + } + + if ( ! content || typeof content === 'function' ) { + return EMPTY_ARRAY; + } + + let _blocks = parsedBlocksCache.get( entityRecord ); + + if ( ! _blocks ) { + _blocks = parse( content ); + parsedBlocksCache.set( entityRecord, _blocks ); + } + + return _blocks; + }, [ id, editedBlocks, content ] ); + const updateFootnotes = useCallback( ( _blocks ) => updateFootnotesFromMeta( _blocks, meta ), [ meta ]