• I need to remove an inner block programmatically. Both the parent and the inner blocks are custom blocks I developed.

    So in my edit.js file in the parent block, I’m importing the action this way:

    const { removeBlocks } = useDispatch("core/block-editor");

    Then, within my handleRemoveBlock() function, I’m doing this:

    let innerBlocks = [...inner_blocks];
    const blockToRemove = innerBlocks.splice(0, 1);
    console.log(blockToRemove); //This returns the correct block.
    
    const clientIds = blockToRemove.map( block => block.clientId );
    console.log(clientIds); //This returns the correct clientId.
    
    const result = removeBlocks( clientIds );
    console.log(result); //This returns PromiseState: "fulfilled" PromiseResult: undefined

    And this is not working. The block never gets removed.

    By the way, I set templateLock to false.

    What I’m doing wrong?

    Thanks.

Viewing 2 replies - 1 through 2 (of 2 total)
  • It looks like you’re on the right track with your code, but there may be a couple of issues that are preventing the block from being removed.

    Firstly, you’re using the splice method to remove the first item from the innerBlocks array, which should work, but you may want to make sure that you’re actually modifying the correct array. You could try logging the innerBlocks array before and after the splice method to confirm that it’s being modified correctly.

    Secondly, the removeBlocks action is asynchronous and returns a promise, so you need to make sure that you’re handling the promise correctly. You could try using async/await or .then() syntax to wait for the promise to resolve before continuing with your code.

    Here’s an example of how you could modify your code to handle these issues:

    const { removeBlocks } = useDispatch(“core/block-editor”);

    const handleRemoveBlock = async () => {
    let innerBlocksCopy = […inner_blocks];
    const blockToRemove = innerBlocksCopy.splice(0, 1)[0];
    console.log(blockToRemove);

    const result = await removeBlocks(blockToRemove.clientId);
    console.log(result);

    // Update state or perform other actions after block removal
    };

    In this example, we’re using async/await syntax to wait for the promise returned by removeBlocks to resolve before logging the result. We’re also directly accessing the first item in the innerBlocksCopy array returned by splice using the [0] index notation.

    I hope this helps!

    Regards
    Anwar

    Thread Starter nelsonamaya

    (@nelsonamaya)

    @anwar4870 thanks for your answer!

    I tried with your example, and the first console.log returns the correct block, however the second one (result), returns undefined.

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘removeBlocks() not working’ is closed to new replies.