plugin development – Setting global block attribute value

Question

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.

  1. Storing the attributes in the database using update_option but I did not see any get_option for the Gutenberg block.
  2. wp.data.subscribe way of dispatching to the blocks required.
  3. 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?

0
m4n0 1 month 2022-07-03T07:04:02-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse