How to render list each time when array is update

Is it possible and how to render list each time when an array is updated? For example I have this layers button which render list of all layers in active document, but I don’t know how to automatically update list each time when I add or remove some layer, without clicking. I tried some options with useState and useEffect but obviously I don’t know how to use them properly.

import ps from "photoshop";

const Layers = () => {
    const layersArray = []
    const layersLength = ps.app.activeDocument.layers.length;
    const layers = ps.app.activeDocument.layers;
    for(var i=0; i<layersLength ; i++){
           layersArray.push(layers[i].name);
    }
    return(
            <div className="toolName">Layers</div>
            <div className="board">
            {layersArray.map((e,index)=>{
                        return(
                                <sp-checkbox key={index} size="m">{e}</sp-checkbox>
                        )
                    })}
            </div>
    )
}

export default Layers;

Perhaps you could attach to an event of layer creation and update the list?

I’m not sure if there is an actual layer event, but I’d imagine so.

//log every event PS does
// app.eventNotifier = (event, descriptor) => {
// console.log(event, JSON.stringify(descriptor, null, ’ '));
// }

I’d run your code, clear the UXP debug console and then add a layer and watch if it hears anything.

if you want to make plugin which detects current layer automatically,
I think you need to use event on Photoshop.

setting layer event like below the code.

const { app } = require("photoshop");
const photoshop = require("photoshop");

const listener = (e) => {
    console.log(e);// param is event name. 
    console.log([...app.activeDocument.layers]);// detecting current layers.
};

const installLayerEvent = () => {
// addNotificationListener receives parameter, firstly event names as an array and call back function,
   // set, make , delete, all of them are events relative with layer.
  // "listener" callback function will be fired when layer is added or deleted or renamed.
     photoshop.action.addNotificationListener(["make", "set", "delete"], listener);
};

installLayerEvent();

any layer added, “make” event can detect it.
“set” event detects changed layer name and “delete” event detects deleting layer.
but to detect any kind of event on layer, you need to inspect more event I suppose.
there are more events on Photoshop.

you can see detail below the link.

https://developer.adobe.com/photoshop/uxp/2022/ps_reference/media/photoshopaction/#addnotificationlistener

using Photoshop event system and useEffect, useState, you can develop plugin you want .

1 Like

Definitely, this is correct answer, because I missed what would trigger array update, and that is exactly this listener. Now its left to manage, to put it all together, pray for me :pray: :smiley: