Run the edit function of parent block when something changes in InnerBlocks

Question

I have a Gutenberg block with a couple of inner blocks (using InnerBlocks from wordpress user/block-editor).

In the edit function, I pull the attributes of all inner blocks and put them in an array.

There is one case when it doesn’t work.
If I create a new inner block in WordPress admin, then change some settings inside this block, then not clicking anywhere else, click the “Update” button, the attributes of the last inner block will not be pulled because between changing settings inside this block and clicking “Update” the edit function of the parent block didn’t run.

Is there any way to trigger the edit function of the parent block in case of changing any attribute in any of the inner blocks?

Here is how the edit function of the parent block looks now:


import { InnerBlocks } from 'wordpress user/block-editor'
import { select } from 'wordpress user/data'
import { __ } from 'wordpress user/i18n'

const EditWrapperBlock = ({
    setAttributes,
    attributes,
    clientId
  }) => {

  const {
    innerBlocks
  } = attributes

  const parentBlock = select( 'core/block-editor' ).getBlocksByClientId( clientId )[ 0 ];
  const childBlocks = parentBlock ? parentBlock.innerBlocks : [];
  const newInnerBlocks = []
  childBlocks.forEach(element => {
    const postType = element.name.slice(element.name.indexOf("https://wordpress.stackexchange.com/") + 1)
    const childBlockAttributes = {postType, ...element.attributes}
    newInnerBlocks.push(childBlockAttributes)
  });

  if (innerBlocks
      && childBlocks
      && childBlocks.length > 0
      && (innerBlocks.length !== childBlocks.length || JSON.stringify(innerBlocks) !== JSON.stringify(newInnerBlocks))) {
    setAttributes({ innerBlocks: newInnerBlocks })
  }


  return (
    <>
      <div className="wrapper-editor">
        <InnerBlocks
          allowedBlocks={[
            'blocks/block1',
            'blocks/block2',
            'blocks/block3',
          ]}
          template={[
            ['blocks/block']
          ]}
        />
      </div>
    </>
  )
}

0
Dmitryi Kodenskyi Hyperion 2 months 2022-06-03T08:46:56-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse