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:
Namespace | wp namespace | npm package |
---|---|---|
core | wp.coreData.store | @wordpress/core-data |
core/blocks | wp.blocks.store | @wordpress/blocks |
core/block-editor | wp.blockEditor.store | @wordpress/block-editor |
core/editor | wp.editor.store | @wordpress/editor |
core/edit-post | wp.editPost.store | @wordpress/edit-post |
core/notices | wp.notices.store | @wordpress/notices |
Leave a Reply