Can't rename instances immediately after swapping the component

I was trying to keep names of instances upon swapping, but it turns out for some reason it needs a delay before I can write a new name. Here is the code and the file for testing:

function delay(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function main() {
  const comp1 = figma.root.findOne(
    (n) => n.name === "Layer / Vector copy" && n.type === "COMPONENT"
  );
  const comp2 = figma.root.findOne(
    (n) => n.name === "Layer / Vector" && n.type === "COMPONENT"
  );

  const instances = figma.root.findAll((n) => n.mainComponent === comp2);
  for (var i = 0; i < instances.length; i++) {
    const inst = instances[i];
    const name = inst.name;
    inst.mainComponent = comp1;
    await delay(100) // comment this line to break renaming
    inst.name = name;
    const namesDifferent = inst.name !== name;
    console.log(namesDifferent, "|", inst.name, name); // will be different
  }
}

main().then(() => {
  figma.closePlugin();
});

If I wait 100ms (very bad when processing lots of instances), renaming works fine: inst.name = name sets the correct name and it’s printed in the console afterwards correctly. But if you don’t wait, the name change simply gets ignored and as a result instances don’t keep their names. I tried shortening the delay but it’s not reliable, works 50% of the time. I don’t think this happened before, at least I never had issues with this in the past and I’ve worked with instances renaming a lot.

1 Like

Same for me. I’ve dealt with it reading old name property one more time. Works in 100% of cases.

Example:

   let oldName = neededNode.name
   neededNode.mainComponent = styledComponent
   let newName = neededNode.name
   neededNode.name = oldName
1 Like

Oh that’s a nice workaround, thanks!