I have a block with some settings that affect the editor only. So not the output. The issue is that when I change these settings, the output doesn’t change. Then WordPress does not detect the change, and does not trigger the “update” button. Next time I open the post the changes to my block-level settings are gone, because they were not saved.

Can I manually trigger the update button from my block?

code

import Edit from "./components/edit/edit"
import PreviewInEditor from "./components/edit/editor-preview";
import BlockSettings from "./components/block-settings/BlockSettings";
import { useBlockProps } from '@wordpress/block-editor';

export default function Editor( props ) {

    function update_settings( settings ) {
        props.setAttributes( { ...props.attributes, settings } );
    }

    if( props.isSelected || props.attributes.price_records.length === 0 ) {
        return ( <div { ...useBlockProps() }>
            <Edit {...props} /> 
            <BlockSettings settings={props.attributes.settings} onChange={update_settings} />
        </div> );
    } else {
        return ( <div { ...useBlockProps() }>
            <PreviewInEditor {...props} />
            <BlockSettings settings={props.attributes.settings} onChange={update_settings} />
        </div>);
    }

}

1 Answer
1

Actually an assumption I made in the question was wrong; The update button doesn’t only change when the output of the save function changes. It also changes when the attributes are changed.

However I found a small bug, which you can’t really see it in the provided code. In my BlockSettings component I was using useState to update the settings inside to the component. I would also emit the settings immidiately after assigning them.

useState is however an async function. So in fact I was emitting the old value. Since I emitted the old value the attributes were identical to the values before. Therefore not triggering an update.

The fix was quite easy. Using useEffect to react on the changed value did the trick for me.

So if the update button isn’t triggering, doublecheck if you actually changed the attributes.

Leave a Reply

Your email address will not be published. Required fields are marked *