1

I'm developing a custom plugin with react and I would like to create a unique identifier for each new added instance of my custom block as soon as it is added to the page.

So I add my "custom block" and the code runs once to create and assign the id. When I visit the backend again, the code should not run again. But if I add a new instance of my "custom block", the code runs once again for this instance and creates & assigns a new id. So I guess I'm looking for a hook like "blockAddedToPage" or so, but I can't find something matching.

I know that there is the clientid, but I need something permanent and shorter :D

I wrote a small helper function to create my id, but how do I run it only when the block is added to the page?

3
  • What will this code do? It's not possible to answer this without the context, what you want might not need what you're asking for in the way you think it does. E.g. in some situations the solution is useEffect, but there are times when that is definitely not the solution. So is watching the data store, filters, and it may be that you're headed down a dead end, a lot of people who ask this are trying to do something they shouldn't that leads to lots of new problems. Give us some context for what you're trying to do to make the question answerable, and eliminate possibilities
    – Tom J Nowell
    Sep 30 at 13:24
  • 1
    @TomJNowell updated :)
    – Lenita
    Sep 30 at 13:30
  • is this unique ID represented anywhere else on the site? Blocks are just content at the end of the day, think of them as a super-fancy shortcode or HTML tag, they aren't a sub-division of posts. What is the unique ID going to be used for? Is it like a ticket number? Is it unique to that post?
    – Tom J Nowell
    Sep 30 at 13:38
0

You can do this with a block attribute and useEffect() in your edit function:

useEffect(() => {
    // If the ID is already set, we don't need to do anything
    if (attributes.id) {
        return;
    }

    // The ID attribute isn't set, so we'll create it and set it now
    setAttributes({
        id: 123, // This is just for example purposes, you can set up your ID however you want
    });
}, []); // Empty array ensures this effect only runs once

One thing to note: This will not run your ID creation code again if you copy/paste/duplicate an existing block with an existing ID attribute.

If you're looking for a more robust solution to generating a unique ID for a block (and are ok with the ID possibly changing), I used a similar technique (see code here) for a block of mine that combines the post ID and an instance ID to create the unique ID. If you rearrange the blocks, insert new ones, etc. it regenerates the IDs as necessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.