Gutenberg: how to insert a reusable block in the editor with JavaScript

Accessing core blocks and custom made blocks, is pretty straight forward. For example, if you want to get the paragraph block, you could do so with:

wp.data.select( 'core/blocks' ).getBlockType('core/paragraph');

And if you want to insert a paragraph, you can easily do so with:

const block = wp.blocks.createBlock( 'core/paragraph', { content: 'hello world!' } );
wp.data.dispatch( 'core/editor' ).insertBlocks( block );

There’s even a convenient way to get ALL registered blocks as an array with

wp.data.select( 'core/blocks' ).getBlockTypes();

However, this function will not return your reusable blocks. It will return a block called 'core/block'. And it turns out that each one of your reusable blocks is actually of this type. But How do we insert a reusable block then? Can we simply do:

const block = wp.blocks.createBlock( 'core/block' );
wp.data.dispatch( 'core/editor' ).insertBlocks( block );

That won’t work, because we need to define which reusable block to insert. 'core/block' has a ref attribute that takes the post_id of a reusable block. So how do we get that?

Reusable blocks are actually saved as a post type called wp_block. So we can get them the same way that we get the posts from any other post type:

const wpBlocks = wp.data.select('core').getEntityRecords('postType', 'wp_block', { per_page: -1 });

Note: if you run this code in your console, you need to run it twice. (because the promise needs to be resolved blah blah …)

OK, so now we end up with a list of our reusable blocks. Now let’s say I want to insert my (already existing) reusable block with the title “About BDWM”. We can find it in the array like this:

const aboutBlock = wpBlocks.find(post => post.title.raw === "About BDWM");

And finally we can insert the reusable block, if it exists, like this:

if (aboutBlock) {
  const block = wp.blocks.createBlock( 'core/block', { ref: aboutBlock.id } );
  wp.data.dispatch( 'core/editor' ).insertBlocks( block );
}