Monday, December 12, 2022
HomeProgrammingSaving Settings for a Customized WordPress Block within the Block Editor

Saving Settings for a Customized WordPress Block within the Block Editor


We’ve achieved a bunch of stuff on this collection! We created a customized WordPress block that fetches information from an exterior API and renders it on the entrance finish. Then we took that work and prolonged it so the information additionally renders immediately within the WordPress block editor. After that, we created a settings UI for the block utilizing parts from the WordPress InspectorControls bundle.

There’s one final bit for us to cowl and that’s saving the settings choices. If we recall from the final article, we’re technically capable of “save” our alternatives within the block settings UI, however these aren’t truly saved wherever. If we make a couple of alternatives, save them, then return to the publish, the settings are utterly reset.

Let’s shut the loop and save these settings so that they persist the following time we edit a publish that accommodates our customized block!

Working With Exterior APIs in WordPress Blocks

Saving settings attributes

We’re working with an API that gives us with soccer soccer crew rating and we’re utilizing it to fetch for displaying rankings based mostly on nation, league, and season. We will create new attributes for every of these like this:

// index.js

attributes: {
  information: {
    sort: "object",
  },
  settings: {
    sort: "object",
    default: {
      nation: {
        sort: "string",
      },
      league: {
        sort: "string",
      },
      season: {
        sort: "string",
      },
    },
  },
},

Subsequent, we have to set the attributes from LeagueSettings.js. At any time when a ComboboxControl is up to date in our settings UI, we have to set the attributes utilizing the setAttributes() methodology. This was extra straightfoward after we had been solely working with one information endpoint. However now that we now have a number of inputs, it’s somewhat extra concerned.

That is how I’m going to prepare it. I’m going to create a brand new object in LeagueSettings.js that follows the construction of the settings attributes and their values.

// LeagueSettings.js

let localSettings = {
  nation: attributes.settings.nation,
  league: attributes.settings.league,
  season: attributes.settings.season,
};

I’m additionally going to alter the preliminary state variables from null to the respective settings variables.

// LeagueSettings.js

const [country, setCountry] = useState(attributes.settings.nation);
const [league, setLeague] = useState(attributes.settings.league);
const [season, setSeason] = useState(attributes.settings.season);

In every of the handle______Change(), I’m going to create a setLocalAttributes() that has an argument that clones and overwrites the earlier localSettings object with the brand new nation, league, and season values. That is finished utilizing the assistance of the unfold operator.

// LeagueSettings.js

perform handleCountryChange(worth) {
  // Preliminary code
  setLocalAttributes({ ...localSettings, nation: worth });
  // Remainder of the code
}

perform handleLeagueChange(worth) {
  // Preliminary code
  setLocalAttributes({ ...localSettings, league: worth });
  // Remainder of the code
}

perform handleSeasonChange(worth) {
  // Preliminary code
  setLocalAttributes({ ...localSettings, season: worth });
  // Remainder of the code
}

We will outline the setLocalAttributes() like this:

// LeagueSettings.js

perform setLocalAttributes(worth) {
  let newSettings = Object.assign(localSettings, worth);
  localSettings = { ...newSettings };
  setAttributes({ settings: localSettings });
}

So, we’re utilizing Object.assign() to merge the 2 objects. Then we are able to clone the newSettings object again to localSettings as a result of we additionally have to account for every settings attribute when there a brand new choice is made and a change happens.

Lastly, we are able to use the setAttributes() as we do usually to set the ultimate object. You’ll be able to verify if the above attributes are altering by updating the alternatives within the UI.

One other technique to verify is to do a console.log() in DevTools to seek out the attributes.

The block added to a post in the block editor with DevTools open showing the saved attributes.

Look nearer at that screenshot. The values are saved in attributes.settings. We’re capable of see it occur stay as a result of React re-renders each time we make a change within the settings, due to the useState() hook.

Displaying the values within the blocks settings UI

It isn’t very helpful to retailer the setting values within the management choices themselves since every one relies on the opposite setting worth (e.g. rankings by league depends upon which season is chosen). However it is vitally helpful in conditions the place the settings values are static and the place settings are unbiased of one another.

With out making the present settings difficult, we are able to create one other part contained in the settings panel that reveals the present attributes. You’ll be able to select your technique to show the settings values however I’m going to import a Tip element from the @wordpress/parts bundle:

// LeagueSettings.js
import { Tip } from "@wordpress/parts";

Whereas I’m right here, I’m going to do a conditional examine for the values earlier than displaying them contained in the Tip element:

<Tip>
  {nation && league && season && (
    <>
      <h2>Present Settings: </h2>
      <div className="current-settings">
        <div className="nation">
          Nation: {attributes.settings.nation}
        </div>
        <div className="league">
          League: {attributes.settings.league}
        </div>
        <div className="season">
          Season: {attributes.settings.season}
        </div>
      </div>
    </>
  )}
</Tip>

Right here’s how that winds up working within the block editor:

API information is extra highly effective when stay information could be proven with out having to manually replace them each time. We are going to look into that within the subsequent installment of this collection.


Saving Settings for a Customized WordPress Block within the Block Editor initially printed on CSS-Methods, which is a part of the DigitalOcean household. It is best to get the e-newsletter.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments