Gutenberg: Block validation failed

In short, when saving an attribute, make sure its type matches the one that you defined in the block’s attributes option.

The docs says:

Lastly, make sure that you respect the data’s type when setting
attributes, as the framework does not automatically perform type
casting of meta. Incorrect typing in block attributes will result in a
post remaining dirty even after saving (cf. isEditedPostDirty,
hasEditedAttributes). For instance, if authorCount is an integer,
remember that event handlers may pass a different kind of data, thus
the value should be cast explicitly:

function onChange( event ) {
  props.setAttributes( { authorCount: Number( event.target.value ) } );
}

So the problem is with the postcount attribute, which is defined as a number, yet saved as a string (event.target.value, in your case, is a string).

And with your code now, if you set the postcategory to foo and the postcount to something else than 6, e.g. 3, the block HTML output would be:

<!-- wp:fare/list-posts {"postcategory":"foo"} -->
[list-posts type="post" category="foo" count="3"][/list-posts]
<!-- /wp:fare/list-posts -->

but it should actually be — note the "postcount":3:

<!-- wp:fare/list-posts {"postcategory":"foo","postcount":3} -->
[list-posts type="post" category="foo" count="3"][/list-posts]
<!-- /wp:fare/list-posts -->

And here’s the problematic code:

// In updatePostCount()
props.setAttributes({postcount: event.target.value})

which should be written as:

props.setAttributes({postcount: Number( event.target.value )})

I.e. You need to explicitly cast the value to a number and not passing the value as-is (a string).

Leave a Comment

tech