Skip to content

Commit

Permalink
Fix Query block undo trap during creation (#30203)
Browse files Browse the repository at this point in the history
  • Loading branch information
ntsekouras authored Mar 25, 2021
1 parent 19fa71b commit 6be973b
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions packages/block-library/src/query/edit/index.js
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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 } );
Expand All @@ -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.
Expand All @@ -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 ] );
Expand Down

0 comments on commit 6be973b

Please sign in to comment.