I’ve a customized Gutenberg block that’s nested inside a question loop block, and I need to save the put up ID as an attribute on every occasion of the block.
This is a simplified model of the block’s edit.js
const Edit = ( props ) => {
const { attributes: { blockId }, context: { postId }, setAttributes } = props;
useEffect( () => {
setAttributes( { blockId: postId } );
});
return (
<div { ...useBlockProps() }>
PostID: { postId }
BlockID: { blockId }
</div>
);
};
export default Edit;
The difficulty I am having is that whereas each postId
and blockID
are displaying appropriately within the Editor, on the front-end each blockId
is being set to the identical worth; the ID of the primary put up within the loop.
I am guessing that is to do with the render operate firing a number of instances, which I used to be making an attempt to mitigate with UseEffect
. For some purpose it isn’t working on this occasion.
Additionally, whereas sometimes I might wrap setAttributes in an if assertion:
if ( !blockId ) {
setAttributes( { blockId: postId } );
}
On this case, the blockId
by some means already appears to be set to the postId
, so setAttributes
would not fireplace with the if assertion current. I am undecided why that is.
What’s the easiest way to drag within the postId from context and set it to the blockId attribute in order that it may be used on the front-end?