From d477b5658d053f55daaa0e23095c4c502c0e7614 Mon Sep 17 00:00:00 2001 From: ntsekouras Date: Wed, 24 Mar 2021 19:10:46 +0200 Subject: [PATCH] Fix Query block undo trap during creation --- packages/block-library/src/query/edit/index.js | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/packages/block-library/src/query/edit/index.js b/packages/block-library/src/query/edit/index.js index 05f60afcf39af..ce83e54e6c97a 100644 --- a/packages/block-library/src/query/edit/index.js +++ b/packages/block-library/src/query/edit/index.js @@ -1,7 +1,7 @@ /** * WordPress dependencies */ -import { useSelect } from '@wordpress/data'; +import { useSelect, useDispatch } from '@wordpress/data'; import { useInstanceId } from '@wordpress/compose'; import { useEffect } from '@wordpress/element'; import { @@ -22,6 +22,9 @@ import { DEFAULTS_POSTS_PER_PAGE } from '../constants'; const TEMPLATE = [ [ 'core/query-loop' ] ]; export function QueryContent( { attributes, setAttributes } ) { const { queryId, query, layout } = attributes; + const { __unstableMarkNextChangeAsNotPersistent } = useDispatch( + blockEditorStore + ); const instanceId = useInstanceId( QueryContent ); const blockProps = useBlockProps(); const innerBlocksProps = useInnerBlocksProps( {}, { template: TEMPLATE } ); @@ -32,6 +35,12 @@ export function QueryContent( { attributes, setAttributes } ) { +getSettings().postsPerPage || DEFAULTS_POSTS_PER_PAGE, }; }, [] ); + // There are some effects running where some initialization logic is + // happening and setting some values to some attributes (ex. queryId). + // These updates can cause an `undo trap` where undoing will result in + // resetting again, so we need to mark these changes as not persistent + // with `__unstableMarkNextChangeAsNotPersistent`. + // Changes in query property (which is an object) need to be in the same callback, // because updates are batched after the render and changes in different query properties // would cause to overide previous wanted changes. @@ -41,13 +50,15 @@ export function QueryContent( { attributes, setAttributes } ) { newQuery.perPage = postsPerPage; } if ( !! Object.keys( newQuery ).length ) { + __unstableMarkNextChangeAsNotPersistent(); updateQuery( newQuery ); } - }, [ query.perPage, query.inherit ] ); + }, [ query.perPage ] ); // We need this for multi-query block pagination. // Query parameters for each block are scoped to their ID. useEffect( () => { if ( ! queryId ) { + __unstableMarkNextChangeAsNotPersistent(); setAttributes( { queryId: instanceId } ); } }, [ queryId, instanceId ] );