Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why useEffect in EditComponent? #16

Open
james0r opened this issue Jul 20, 2023 · 0 comments
Open

Why useEffect in EditComponent? #16

james0r opened this issue Jul 20, 2023 · 0 comments

Comments

@james0r
Copy link

james0r commented Jul 20, 2023

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 />
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant