Instantly access figma.currentPage.selection nodes

Currently, this is my code in code.ts file:

figma.ui.onmessage = msg => {

  if (msg.type === 'option-selected') {
    let toSelect = []
  
    for (const node of figma.currentPage.selection) {
      if (node.type === "TEXT") {
        toSelect.push(node)
      }
    }
}

code in .tsx file:

<p onClick={() => parent.postMessage({ pluginMessage: { type: 'option-selected', option } }, '*')}>
    {hit.content}
</p>

However, this is not the behaviour I want now (to use msg.type === ‘option-selected’). I want to instantly have access to the nodes that have been selected and work with them accordingly.

How can I do this and in which file(.tsx or code.ts)?

You can access figma.currentPage.selection in any place in code.ts file. No need to wait for the message from the UI, if that’s what you are asking.

Hello Gleb, I understand this. But, what I want my plugin to do is this:

AFTER the plugin has been run, it constantly checks if a node has been selected (by user simply clicking on a node).

Use the selectionchange event in figma.on.

figma.on("selectionchange", () => { //Your code })