plugin development – Setting global block attribute value
I have a scenario where I will have to use the same API key for all the blocks that is present and that will be created new. So when user inputs on one block through a form, it will update on all the blocks of the namespace instantly.
Currently when register_block_type()
and props.setAttributes
method is used, the values for each attribute is unique for each of the block. I have seen the documentation. I couldn’t see a standard way for sharing the same value across blocks.
Register code:
registerBlockType("namespace", {
title: "Plugin title",
category: "common",
attributes: {
apiKey: { type: "string" },
Handling submit from the form inside InspectorControls:
<InspectorControls>
<PanelBody>
<form id="api-key-input" onSubmit={(e) => handleSubmit(e)}>
<input
type="password"
ref={inputRef}
defaultValue={props.attributes.apiKey}
/>
<input type="submit" />
</form>
</InspectorControls>
function handleSubmit(e) {
e.preventDefault();
props.setAttributes({ apiKey: inputRef.current.value });
}
The methods that I have looked at so far.
- Storing the attributes in the database using
update_option
but I did not see anyget_option
for the Gutenberg block. wp.data.subscribe
way of dispatching to the blocks required.- Creating a registry store and managing the overall value using states.
Is there an easiest/safest way of doing this that I am missing, like setting an option or supports value?
Leave an answer