Error (node does not exist)

Made a function to search for all instances on the page, and then toggle the ‘Mode’ property values from light to dark, and vice versa. But it stuck after only changing one instance and then I got the error

Error in get_name: The node (instance sublayer or table cell) with id ‘xxxx’ does not exist

Here is the function.

function updateComponentProperties() {
  const page = figma.currentPage;
  // Find all INSTANCE nodes on the current page
  const instanceNodes = page.findAll(node => node.type === 'INSTANCE') as InstanceNode[];
  a = 0;
  for (let i = 0; i < instanceNodes.length; i++) {
    a = a+1;
    console.log('this is iteration ' + a);
    console.log(instanceNodes);
    const node = instanceNodes[i];
    console.log('Opening node:', node.name);
    const componentProperties = node.componentProperties;

    if (componentProperties) {
        console.log('Component properties found:', componentProperties);
        const propertiesToUpdate: { [key: string]: string | boolean } = {};

        for (const propName in componentProperties) {
            const property = componentProperties[propName];
            console.log('Checking property:', propName);

            if (propName === "UniqueMode") {
                const currentValue = property.value as string;
                console.log('Current mode value:', currentValue);

                let newValue: string;
                if (currentValue === lightModeName) {
                    newValue = darkModeName;
                } else if (currentValue === darkModeName) {
                    newValue = lightModeName;
                } else {
                    console.log('Skipping property because it does not match light or dark mode.');
                    continue;
                }

                propertiesToUpdate[propName] = newValue;
                console.log(`Updating "${propName}" from "${currentValue}" to "${newValue}"`);
            }
        }
        if (Object.keys(propertiesToUpdate).length > 0) {
            console.log('loop will stuck after this');
            console.log('Applying updates:', propertiesToUpdate);
            node.setProperties(propertiesToUpdate);
        }
    } else {
        console.log(`No component properties found for node "${node.name}"`);
    }

When you swap instances, internal nodes change to different ones. So you need to search through them again.

Would you elaborate on this and give me some more specific pointers on which part of the code I need to revise? Thanks

Instead of first searching and then swapping, I would combine the two. Search the file and swap properties as you go.