Storing principal id

Hi, I’m currently working with Plug wallet and trying to store the Principal during switching account. The problem is when I tried to useState to update the ID, it runs again the Connect Wallet. How can I keep updating the Principal without having to Reconnect Wallet twice?
Here’s my code

  const [currentID, setCurrentID] = useState("NICE");

  (async () => {
    // Canister Ids
    const nnsCanisterId = 'ryjl3-tyaaa-aaaaa-aaaba-cai'

    // Whitelist
    const whitelist = [
      nnsCanisterId,
    ];
  
    // Host
    const host = "http://localhost:8080/";
  
    // Callback to print sessionData
    const onConnectionUpdate = () => {
      setCurrentID(window.ic.plug.sessionManager.sessionData.principalId);
    };
    
  
    // Make the request
    try {
      const publicKey = await window.ic.plug.requestConnect({
        whitelist,
        host,
        onConnectionUpdate,
        timeout: 50000
      });
      console.log(`The connected user's public key is:`, publicKey);
    } catch (e) {
      console.log(e);
    }
  })();

It looks like you’re using React here -

Your whole function will run every render - consider using a useEffect hook with a list of values to watch changes for to prevent unnecessary re-runs. I think once you have the publicKey, you shouldn’t need to run requestConnect again, right?

Also, assuming you’re just getting started, the PrincipalId is not enough to make requests. You’ll need to have an Actor that is set up with an Identity. The principalId is derived from the Identity, but just represents the public key. It can’t be used to create the cryptographic signatures we use when talking to the IC

1 Like

Hi thank you for spending time answering, after a long time digging around I found some walks around that works for me

For the solution, I want to stay update when the user has changed the account but that pretty impossible (I asked the Plug dev teams), the walk around is adding the ‘Change account’ button.
I’ll make the pops up requestConnect and get again, than get the new principal id instead of silently update them.