Hooks – How to set the post ID from context to an attribute in a child block of a Gutenberg query loop?

I have a custom Gutenberg block nested in a query loop block, and I want to save the post ID as an attribute on each instance of the block.

Here is a simplified version of the block 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 issue I have is that while both postId And blockID are visible correctly in the editor, each on the front end blockId being set to the same value; The ID of the first post in the loop.

I’m guessing it has to do with the render function firing multiple times, which is what I was trying to reduce UseEffect, For some reason it is not working in this example.

Also, normally I would wrap setAttributes in a statement:

if ( !blockId ) {
    setAttributes( { blockId: postId } );
}

in this matter, blockId it seems to have been set somehow already postIdSo setAttributes The if statement does not fire. I am not sure why this is so.

What is the best way to pull the post ID from the context and set it to the blockId attribute so that it can be used on the front-end?

Leave a Comment