Search code examples
wordpresspluginsblockwordpress-gutenberg

Wordpress Gutenberg .updateBlock


There is method I believe I can use for my need. However I need an example of it using: https://developer.wordpress.org/block-editor/data/data-core-editor/#updateBlockAttributes how this is possible? Anyone has it maybe?


Solution

  • You can read the (very tiny) documentation on the function in the Block Editor Handbook. Here is an live example from my own code at a new slider block for wordpress. It uses the withDispatch higher order component to feed components with actions.

    withDispatch( ( dispatch, ownProps, registry ) => {
    
      return {
        updateEditable( isEditing ) {
          const { clientId, setAttributes } = ownProps;
          const { getBlockOrder } = registry.select( 'core/block-editor' );
          const { updateBlockAttributes } = dispatch( 'core/block-editor' );
    
          //update own isEditable
          setAttributes( { isEditing } );
    
          const innerBlockIds = getBlockOrder( clientId );
          innerBlockIds.forEach( ( innerBlockId ) => {
            updateBlockAttributes( innerBlockId, {
             isEditing,
            } );
          } );
        },
      };
    } )
    

    To play around with the wordpress data module, that offers data about the editor or blocks to the client, you can also make use of the wp.data-Module. When in the backend, You can e.g. go to a browser console, and type wp.data.dispatch( 'core/editor' ).updateBlockAttributes() to test what the function does.

    You can also have a look in the gutenberg github repository. Core Blocks also use updateBlockAttributes. E.g. in columns

    If you want more information on data handling in gutenberg, you can read this very good blob post, that introduces the wp.data api and also the concept of withSelect and withDispatch higher order components.