Skip to content

Query: Avoid self-setting attribute antipattern #79328

Closed

Description

@mcsf

Context: an open bug related to multi-entity saving

There is a hard-to-debug issue concerning the multi-entity save flow (#78989) which is currently being examined by several contributors. In a gist, the Site Editor is prone to showing untouched entities as dirty, and there is an ongoing search to determine whether something in the saving/dirtying machinery has changed, and/or whether certain block types are to blame.

Among the findings is the fact that the Query block may automatically set two of its own attributes, query and queryId upon mounting:

useEffect( () => {
const newQuery = {};
// When we inherit from global query always need to set the `perPage`
// based on the reading settings.
if ( inherit && query.perPage !== postsPerPage ) {
newQuery.perPage = postsPerPage;
} else if ( ! query.perPage && postsPerPage ) {
newQuery.perPage = postsPerPage;
}
if ( !! Object.keys( newQuery ).length ) {
__unstableMarkNextChangeAsNotPersistent();
updateQuery( newQuery );
}
}, [

useEffect( () => {
if ( ! Number.isFinite( queryId ) ) {
__unstableMarkNextChangeAsNotPersistent();
setAttributes( { queryId: instanceId } );
}

Solutions

At the very least, we should mitigate these self-changing effects. For example, #79000 mitigated the Navigation block's self-changing behaviour by only triggering the effect if the block or its descendants are selected.

Ideally, though, we'd get rid of that behaviour altogether, but that requires ad-hoc solutions. For example, #79048 introduced a new attribute passed as context from Navigation Submenu to its Page List descendants.

/cc @ntsekouras

Activity

  1. added
    [Type] Bug
    on Jun 18, 2026
  2. ntsekouras commented on Jun 18, 2026

    @ntsekouras
    Contributor

    This shouldn't cause any dirtying state because both instances have __unstableMarkNextChangeAsNotPersistent.

    That said, I'm not sure how we can avoid this unless we have an API for blocks to indicate something like uniqueId that would have to handle such assignment in a lower level. The reason for setting this attribute like that is because there can be multiple Query Loop blocks in a page and the pagination for each block is tied to a unique id in order to work properly.

    It has been discussed in some places (quite a lot), among other similar cases for block attributes that shouldn't persist when duplicating blocks etc.. You've also participated in the main issue's discussions 😄 .

  3. mcsf commented on Jun 19, 2026

    @mcsf
    ContributorAuthor

    This shouldn't cause any dirtying state because both instances have __unstableMarkNextChangeAsNotPersistent.

    That's the thing: this marking is no longer reliable, and we don't know why yet.

    See for yourself:

    1. Start a new post, add a paragraph with some text, save draft
    2. Apply the patch attached below
    3. Rebuild and refresh -> notice the editor getting dirty, and look at the console
    Details
    diff --git a/packages/block-editor/src/components/block-edit/edit.js b/packages/block-editor/src/components/block-edit/edit.js
    index bb98776479a..91b70a385bd 100644
    --- a/packages/block-editor/src/components/block-edit/edit.js
    +++ b/packages/block-editor/src/components/block-edit/edit.js
    @@ -187,6 +187,11 @@ const EditWithGeneratedProps = ( props ) => {
     	const setBoundAttributes = useCallback(
     		( nextAttributes ) => {
     			if ( ! blockBindings ) {
    +				console.log(
    +					'setAttributes called for type %s',
    +					name,
    +					nextAttributes
    +				);
     				setAttributes( nextAttributes );
     				return;
     			}
    diff --git a/packages/block-library/src/paragraph/edit.js b/packages/block-library/src/paragraph/edit.js
    index 1c7ddb429fb..b799e9d64f2 100644
    --- a/packages/block-library/src/paragraph/edit.js
    +++ b/packages/block-library/src/paragraph/edit.js
    @@ -21,9 +21,11 @@ import {
     	useBlockEditingMode,
     	store as blockEditorStore,
     } from '@wordpress/block-editor';
    -import { useSelect } from '@wordpress/data';
    +import { useDispatch, useSelect } from '@wordpress/data';
     import { getBlockSupport } from '@wordpress/blocks';
     import { formatLTR } from '@wordpress/icons';
    +import { useEffect } from '@wordpress/element';
    +
     /**
      * Internal dependencies
      */
    @@ -132,6 +134,16 @@ function ParagraphBlock( {
     	} );
     	const blockEditingMode = useBlockEditingMode();
     
    +	const { __unstableMarkNextChangeAsNotPersistent } =
    +		useDispatch( blockEditorStore );
    +
    +	useEffect( () => {
    +		__unstableMarkNextChangeAsNotPersistent();
    +		setAttributes( {
    +			placeholder: ( attributes.placeholder ?? '' ) + 'foo',
    +		} );
    +	}, [] );
    +
     	return (
     		<>
     			{ blockEditingMode === 'default' && (
  4. mcsf commented on Jun 19, 2026

    @mcsf
    ContributorAuthor

    Let's tackle the offending attributes one by one, starting with what looks like the easiest. It's possible I'm oversimplifying things, so feel free to call me out.

    query.perPage

    From what I see, there seem to be different things we want to ensure:

    • Accurate in-editor previews of the final result, which is why the posts_per_page value from getEntityRecordEdits trumps getEntityRecord.
    • Honouring posts_per_page as a default but letting users override it... unless the query is inherited, in which case their preference is overridden.

    However, the desire for accuracy in the end means that now query.perPage is frozen inside the block's attributes. So, if the admin changes the site's PPP setting globally, that behaviour won't apply to templates with query loops unless the admin opens them in the editor again and saves them. Correct?

    Wouldn't the following alternative work just as well, if not better?

    • The query attribute stays as is, with query.perPage defaulting to null
    • The useEffect call is removed
    • The editing UI can still adapt to circumstances, like hiding the perPage control if inherit is true
    • Hence, in the serialised block, query.perPage can theoretically be null or a number regardless of inherit (because we don't force the value using useEffect)
    • Instead, in the editor, the "real" per-page value is computed as such:
      • If query.perPage is greater than zero and inherit is false, then use query.perPage
      • If query.perPage is greater than zero and inherit is true, then use getEntityRecordEdits || getEntityRecord
      • If query.perPage is null, then use getEntityRecordEdits || getEntityRecord
    • In the render callback, the same logic is used, but with get_option( 'posts_per_page' )
  5. ntsekouras commented on Jun 19, 2026

    @ntsekouras
    Contributor

    That's the thing: this marking is no longer reliable, and we don't know why yet.

    I'm not really sure that the issue comes from the selector..

    1. I've tested your scenario a bit differently in Query Loop edit:
    useEffect( () => {
    		__unstableMarkNextChangeAsNotPersistent();
    		setAttributes( {
    			tagName: 'span',
    		} );
    	}, [ __unstableMarkNextChangeAsNotPersistent, setAttributes ] );
    
    • Verified that setAttributes is called (with breakpoints) and in code editor that the attribute is updated.
    • Refresh and no dirty state
    1. Then I tested your patch and in paragraph block and makes the post dirty.
    2. Then I tested your patch and in paragraph block but chose to update the dropCaps prop and does not make the post dirty

    It seems something else is going on, right? Maybe something with specific attribute handling? If it was the selector, it should dirty the post in all cases, no?

  6. ntsekouras commented on Jun 19, 2026

    @ntsekouras
    Contributor

    Let's tackle the offending attributes one by one, starting with what looks like the easiest. It's possible I'm oversimplifying things, so feel free to call me out.

    Should we focus there though? Can you reproduce the dirty post with Query Loop block? I can't personally and that code is like that for many years.

    As I noted above, I think the issue lies elsewhere and while we could try to find a different approach for perPage, I'm not sure how we would handle queryId. If you find a good solution to remove this, I'm all for it of course.

  7. mcsf commented on Jun 19, 2026

    @mcsf
    ContributorAuthor

    Sorry to bombard you with this :)

    Should we focus there though? Can you reproduce the dirty post with Query Loop block? I can't personally and that code is like that for many years.

    If I understood your steps correctly, that is to be expected: since you added the block manually, the attribute is automatically set once after that, then the post is saved, and upon reloading there is nothing else to do. The problem is when there are themes/templates involved: then it becomes likely that, upon loading a "page" in the site editor (or in the post editor with "Show template" on), the blocks are instantiated based on the template's blueprint, but then some of the attributes are automatically corrected.

    In my case I didn't spot it with query.perPage, but yesterday the queryId mutations were one of the attribute changes in my dev env that were dirtying the editor.

    That said, Jarda made a breakthrough in the real problem (#79350), so hopefully we can deescalate this whole matter across our block library and keep relying on __unstableMarkNextChangeAsNotPersistent when need be. However, I do think it's a healthy exercise to think hard (and even revisit, sometimes years later) about the way we use self-setting attributes in our blocks. :)

  8. added
    [Type] Code Quality
    and removed
    [Type] Bug
    on Jun 19, 2026
  9. mcsf commented on Jun 19, 2026

    @mcsf
    ContributorAuthor

    I've adjusted the labels on the expectation that Jarda's PR will fix the real issue soon.

    Question, while we're here examining these attributes: won't queryId be erroneously duplicated if a user duplicates a Query block? (edit: in my testing, yes.)

  10. Mamaduka commented on Jun 19, 2026

    @Mamaduka
    Member

    @ellatrix, was also working to improve per_page setter side-effect - #66532.

    Question, while we're here examining these attributes: won't queryId be erroneously duplicated if a user duplicates a Query block?

    Bingo 😄 Here's the issue - #55823.

  11. ntsekouras commented on Jun 19, 2026

    @ntsekouras
    Contributor

    The problem is when there are themes/templates involved: then it becomes likely that, upon loading a "page" in the site editor

    Ah.. ok. I got the case where this can happen (probably template including Query Loop without a queryId).

    However, I do think it's a healthy exercise to think hard (and even revisit, sometimes years later) about the way we use self-setting attributes in our blocks. :)

    Of course. My question about focusing on that was because I was quite confident it was something else than __unstableMarkNextChangeAsNotPersistent selector.

  12. jsnajdr commented on Jun 23, 2026

    @jsnajdr
    Member

    Now when #79350 is merged, I think this issue is resolved. The QueryContent component correctly marks the queryId and query.perPage updates as non-persistent.

    The only remaining issue I see here is copying queryId on duplication, but that's an unrelated bug?

  13. mcsf commented on Jun 23, 2026

    @mcsf
    ContributorAuthor

    Correct. Per George's comment, there's one bug and one issue for improvement. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    [Type] Code Quality

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions