LearnWebCode / brads-boilerplate-wordpress

An example starter theme and block-type plugin that use @wordpress/scripts for JS & CSS
MIT License
498 stars 192 forks source link

Why useEffect in EditComponent? #16

Open james0r opened 1 year ago

james0r commented 1 year ago

I feel like i'm maybe missing something, but is it critical for your approach to use useEffect and the fetch call in the Banner EditComponent function?

I didn't understand why we were doing this so I just changed it to use setAttributes() and it seems to work the same.

our-blocks/banner.js

import apiFetch from "@wordpress/api-fetch"
import { Button, PanelBody, PanelRow } from "@wordpress/components"
import { InnerBlocks, InspectorControls, MediaUpload, MediaUploadCheck } from "@wordpress/block-editor"
import { registerBlockType } from "@wordpress/blocks"
import { useEffect } from "@wordpress/element"

registerBlockType("ourblocktheme/banner", {
  title: "Banner",
  supports: {
    align: ["full"]
  },
  attributes: {
    align: { type: "string", default: "full" },
    imageId: { type: "number" },
    imageUrl: { type: "string", default: banner.fallbackimage }
  },
  edit: EditComponent,
  save: SaveComponent
})

function EditComponent({ attributes, setAttributes, isSelected }) {
  function onFileSelect(image) {
    setAttributes({ 
      imageId: image.id,
      imageUrl: image.url
    })
  }

  return (
    <>
      <InspectorControls>
        <PanelBody title="Background" initialOpen={true}>
          <PanelRow>
            <MediaUploadCheck>
              <MediaUpload
                onSelect={onFileSelect}
                value={attributes.imageId}
                render={({ open }) => {
                  return <Button onClick={open} className="is-primary">Choose Image</Button>
                }}
              />
            </MediaUploadCheck>
          </PanelRow>
        </PanelBody>
      </InspectorControls>
      <div className="page-banner">
        <div className="page-banner__bg-image" style={{ backgroundImage: `url('${attributes.imageUrl}')` }}></div>
        <div className="page-banner__content container t-center c-white">
          <InnerBlocks allowedBlocks={["ourblocktheme/genericheading", "ourblocktheme/genericbutton"]} />
        </div>
      </div>
    </>
  )
}

function SaveComponent() {
  return <InnerBlocks.Content />
}