• Resolved Fabian Todt

    (@gaambo)


    When developing a custom sidebar for the block editor, a panel in the InspectorControls or a block, there are multiple ways to get the properties/fields for the post:

    1. getEditedPostAttribute
    According to its doc block it “Returns a single attribute of the post being edited, preferring the unsaved edit if one exists, but falling back to the attribute for the last known saved state of the post.”
    When using it like getEditedPostAttribute("meta") it will get the whole meta, but it’s possible to also get other properties. Eg the featured image selector in the sidebar gets the attribute featured_media.

    2. useEntityProp
    According to its doc block it “Hook that returns the value and a setter for the specified property of the nearest provided entity of the specified type.”
    In the metabox to block guide it’s recommended to be used to get the meta like `useEntityProp(“postType”, postType, “meta”)”

    I understand, that the second one is a react hook and the first one would have to be used in a useSelect select mapper.

    But still, what exactly is the difference between these methods?
    What is the preferred way and are there cases in which they don’t return the same data? As far as I can see, both return the current (maybe unsaved) state of the object.


Viewing 3 replies - 1 through 3 (of 3 total)
  • In most cases, the two methods return the same data, as they both retrieve the current (possibly unsaved) state of the object. However, there may be some cases where the two methods do not return the same data, for example if the data has been changed but not saved in the block editor, useEntityProp will return the updated value, while getEditedPostAttribute will return the last saved value.

    Thread Starter Fabian Todt

    (@gaambo)

    Okay, thank you. But doesn’t the doc for getEditedPostAttribute “unsaved edit if one exists” suggest, that also unsaved edits will be returned?

    Yes, that’s correct. The getEditedPostAttribute function returns the unsaved changes if they exist, and if there are no unsaved changes, it returns the attribute from the last known saved state of the post. So it does take into account unsaved edits when returning the data. The useEntityProp hook and getEditedPostAttribute function can return different results if the data has been updated in the block editor but not yet saved. In that case, useEntityProp will return the updated value, while getEditedPostAttribute will return the last saved value.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Difference between useEntityProp and getEditedPostAttribute’ is closed to new replies.