Editor not detecting change with setMeta() unless array items are added or removed
Describe the bug
I'm putting together an editor-only block that manages a single array-type meta value's contents with a "repeater" interface. Everything is working as expected after following the "Meta Block" tutorial with the exception of one thing: The editor doesn't seem to detect a change (therefore enabling the "Update" button) when setMeta() is fired unless an entire item as added or removed from the array. Updating the contents of an existing array item by itself doesn't result in the "Update" button being clickable.
To reproduce Steps to reproduce the behavior:
- Register post meta for the array data
<?php
/**
* Do extra meta post meta registration for attribute sourcing
*
* @since 1.0.0
*/
function whatever_do_meta_registration() {
register_post_meta(
'',
'_schedule_items',
[
'single' => true,
'type' => 'array',
'show_in_rest' => [
'schema' => [
'items' => [
'type' => 'object',
'properties' => [
'time' => [ 'type' => 'string' ],
'activity' => [ 'type' => 'string' ],
],
],
],
],
'auth_callback' => 'get_can_user_edit_posts',
]
);
}
add_action( 'init', 'whatever_do_meta_registration' );
- Register a block without any attributes and a
save:property just returningnull
/**
* Schedule editing block
*
* @since 1.0.0
*/
import { __ } from '@wordpress/i18n';
import { registerBlockType } from '@wordpress/blocks';
import { formatListBullets as icon } from '@wordpress/icons';
import edit from './edit';
registerBlockType( 'events/schedule-edit', {
title: __( 'Schedule Editor', 'events' ),
description: __( "Edit a schedule's items.", 'knight-blocks' ),
icon,
keywords: [ __( 'schedule' ), __( 'plan' ) ],
edit,
save: () => null,
} );
- Create an
edit:property like this:
/**
* Schedule editor block edit
*
* @since 1.0.0
*/
import { __ } from '@wordpress/i18n';
import { useSelect } from '@wordpress/data';
import { useEntityProp } from '@wordpress/core-data';
import { RichText, useBlockProps } from '@wordpress/block-editor';
import { Fragment } from '@wordpress/element';
import { Button, IconButton } from '@wordpress/components';
export default function edit() {
// get block properties (not really sure what this does other than setting
// some attributes on the wrapper div?)
const blockProps = useBlockProps();
// get current post type data
const postType = useSelect(
( select ) => select( 'core/editor' ).getCurrentPostType(),
[]
);
// get meta and meta setter from post
const [ meta, setMeta ] = useEntityProp( 'postType', postType, 'meta' );
// get schedule items array
const items = meta._schedule_items;
// set new schedule items
const updateItems = ( newItems ) => {
setMeta( { ...meta, _schedule_items: newItems } );
};
// add a new, empty item
const handleAddItem = () => {
const newItems = [ ...items ];
newItems.push( {
time: '',
activity: JSON.stringify( '' ),
} );
updateItems( newItems );
};
// remove an item
const handleRemoveItem = ( index ) => {
const newItems = [ ...items ];
newItems.splice( index, 1 );
updateItems( newItems );
};
// handle a single schedule item being edited
const handleActivityChange = ( activity, index ) => {
const newItems = [ ...items ];
newItems[ index ].activity = JSON.stringify( activity );
updateItems( newItems );
};
let itemFields;
// loop through the items and output a field to edit it and a button to
// remove it
if ( items.length ) {
itemFields = items.map( ( thing, index ) => {
return (
<Fragment key={ index }>
<RichText
tagName="p"
value={ JSON.parse( thing.activity ) }
onChange={ ( value ) =>
handleActivityChange( value, index )
}
/>
<IconButton
icon="no-alt"
label={ __( 'Delete Activity', 'events' ) }
onClick={ () => handleRemoveItem( index ) }
/>
</Fragment>
);
} );
}
return (
<div { ...blockProps }>
{ itemFields }
<Button isPrimary onClick={ handleAddItem.bind( this ) }>
{ __( 'Add Activity', 'events' ) }
</Button>
</div>
);
}
- Add the block in your editor (change detected), update post
- Click the "Add Activity" button (change detected) put some text in the
<RichText>, and update post - Change the text in the existing activity you added. Update should not be available :(
- Add another activity. Update should be available. Remove the new activity. Update should be unavailable again.
Expected behavior
Editing an existing item in the meta array, which calls setMeta() the same as adding/removing items should "stage" some kind of change in the block editor that can be updated.
Editor version:
- WordPress version: [e.g: 5.5.3]
- Running Gutenberg plugin 9.5.2, but only because
useBlockProps()causes an error without it. Maybe this was fixed in whatever version was released with 5.6.0?
Desktop (please complete the following information):
- OS: Windows 10 Pro Vesrion 10.0.19041
- Browser: Chrome Version 87.0.4280.88
Thank you!
Ok so I found a temporary workaround by just making the whole attribute a JSON string with the array of items + using the more standard/clean meta interfacing (not using useSelect(), useBlockProps(), useEntityProp(), etc). While I still think this issue is just my misunderstanding or a bug, the following is my resulting code. I believe it'd make more sense and be more performant to have the actual attribute saved as an array though, so it'd be sick if we could get that to work.
Workaround meta registration
<?php
/**
* Do extra meta post meta registration for attribute sourcing
*
* @since 1.0.0
*/
function whatever_do_meta_registration() {
register_post_meta(
'',
'_schedule_items',
[
'single' => true,
'type' => 'string',
'default' => '[]',
'show_in_rest' => true,
'auth_callback' => 'get_can_user_edit_posts',
]
);
}
add_action( 'init', 'whatever_do_meta_registration' );
Workaround editor block registration
/**
* Schedule editing block
*
* @since 1.0.0
*/
import { __ } from '@wordpress/i18n';
import { registerBlockType } from '@wordpress/blocks';
import { formatListBullets as icon } from '@wordpress/icons';
import edit from './edit';
registerBlockType( 'events/schedule-edit', {
title: __( 'Schedule Editor', 'events' ),
description: __( "Edit a schedule's items.", 'knight-blocks' ),
icon,
keywords: [ __( 'schedule' ), __( 'plan' ) ],
attributes: {
items: {
type: 'string',
source: 'meta',
meta: '_schedule_items',
default: '[]',
},
},
edit,
save: () => null,
} );
Workaround block edit prop
/**
* Schedule editor block edit
*
* @since 1.0.0
*/
import { __ } from '@wordpress/i18n';
import { RichText } from '@wordpress/block-editor';
import { Fragment } from '@wordpress/element';
import { Button, IconButton } from '@wordpress/components';
export default function edit( { attributes, setAttributes } ) {
let { items } = attributes;
// convert to array of items
items = JSON.parse( items );
// set items attribute
const updateItems = ( newItems ) => {
setAttributes( { items: JSON.stringify( newItems ) } );
};
// add a new, blank item
const handleAddItem = () => {
const newItems = [ ...items ];
newItems.push( {
time: '',
activity: JSON.stringify( '' ),
} );
updateItems( newItems );
};
// remove item at index
const handleRemoveItem = ( index ) => {
const newItems = [ ...items ];
newItems.splice( index, 1 );
updateItems( newItems );
};
// handle a single schedule item being edited
const handleActivityChange = ( activity, index ) => {
const newItems = [ ...items ];
newItems[ index ].activity = JSON.stringify( activity );
updateItems( newItems );
};
let itemFields;
// loop through the items and create a field to edit it and a button to
// remove it.
if ( items.length ) {
itemFields = items.map( ( thing, index ) => {
return (
<Fragment key={ index }>
<RichText
tagName="p"
value={ JSON.parse( thing.activity ) }
onChange={ ( value ) =>
handleActivityChange( value, index )
}
/>
<IconButton
icon="no-alt"
label={ __( 'Delete Activity', 'events' ) }
onClick={ () => handleRemoveItem( index ) }
/>
</Fragment>
);
} );
}
return (
<Fragment>
{ itemFields }
<Button isPrimary onClick={ handleAddItem.bind( this ) }>
{ __( 'Add Activity', 'events' ) }
</Button>
</Fragment>
);
}
Hi @JordanPak I'm looking through old reports like this one - and just wanted to check if it is something you're still seeing happening?
With no further comments or movement on this, I will close the issue.
If it is still a problem - a new issue can be opened with updated details on how to reproduce.