Hey visitors! If you’re a beginner in WordPress and WP-CLI development, then you should check out my dear friend Bhargav’s Youtube channel! @BuntyWP

A better way to access Gutenberg’s data stores

Often times you will come across a Gutenberg project where you will see data stores accessed using string literals in the following way:

wp.data.dispatch( 'core/edit-post' );Code language: JavaScript (javascript)

or…

wp.data.select( 'core/block-editor' );Code language: JavaScript (javascript)

Now, there’s nothing very wrong about this if it’s used once or twice in the project. But for a large project, there are chances of manual error where you can make a typo.

A disadvantage of using a string literal is the lack of auto-completion. You either have to type the whole thing or you copy-paste it every time.

A better way

Gutenberg exports details of the data store through the store variable. Meaning – If you were to access the core/blocks data like this:

wp.data.select( 'core/blocks' );Code language: JavaScript (javascript)

You can instead import the store details about the core/blocks data store and reuse it every time using the following:

// If you're importing from the package.
import { store as blocksDataStore } from '@wordpress/blocks';

// Or the normal way:
const { store: blocksDataStore } = wp.blocks;Code language: JavaScript (javascript)

The benefit of this is that the variable blocksDataStore will be available for auto-completion in your editor.

This is applicable for all data stores exposed by Gutenberg, but at times it can be difficult to identify where to locate it. For example, you might try to access the core data store as:

const { store: blocksDataStore } = wp.core;Code language: JavaScript (javascript)

…due to the naming convention, but the thing is the core data store is available under wp.coreData

For reference, I have created the table below to access the various data stores:

Namespacewp namespacenpm package
corewp.coreData.store@wordpress/core-data
core/blockswp.blocks.store@wordpress/blocks
core/block-editorwp.blockEditor.store@wordpress/block-editor
core/editorwp.editor.store@wordpress/editor
core/edit-postwp.editPost.store@wordpress/edit-post
core/noticeswp.notices.store@wordpress/notices
Reference table for Gutenberg’s data stores.



Leave a Reply

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

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

The reCAPTCHA verification period has expired. Please reload the page.

Powered by WordPress