[Vuejs]-How to run a function in a singleton file only when electron main process is ready

0👍

Your problem is that const address in your globals.ts is an Immediately Invoked Function Expression, which means it will get executed as soon as the globals.ts file is imported. The way to solve this, is to remove the invocation (the ();) at the very end of the declaration of address to turn the variable into a function.

This will not make it possible for the variable itself to be a singleton, but you can get around that by using a non-exported variable in the file to store the value once it has been retrieved and re-use that when the function is called again. That could look somewhat like this:

const address: string | undefined = undefined;

export const getAddress = async (): Promise<string> => {
  if (address) {
    return address;
  }

  try {
    const hostname: string = await window.ipcRenderer.invoke("getMachineIPv4", "works now");
    const firstThreeNumbers = hostname.split(".")[0];
    const portNumber = "3000";
    const subnet = "10";

    if (firstThreeNumbers === "123") {
      address = `123.123.1111.${subnet}:${portNumber}`;
    } else if (firstThreeNumbers === "101") {
      address = `123.123.111.${subnet}:${portNumber}`;
    } else if (hostname == "localhost") {
      // Default, usually localhost
      address = `123.123.111.${subnet}:${portNumber}`;
    } else {
      console.error("ip address not found");
      return "error";
    }

    return address;
  } catch (error) {
    console.error("Failed to get address:", error);
    return "error";
  }
};

You can then call that function to obtain the address instead of reading it from the variable. When you call the function from the renderer, which can only be started after app.on("ready"), it is guaranteed that your main process will be initialized.

import { getAddress } from "./<path>/<to>/globals.ts";


async function doAddressStuff() {
  const address = await getAddress();

  // more address stuff ...
}

I hope that helps, if anything is unclear, let me know!

Leave a comment