0

I am using this code given below in my react application to listen an account change event but facing issue as no response or error i am getting on changing account form phantom wallet .i have followed the documentation and tried the method using public key as well but still i didn't get any solution the code for the account change listener is given below .

useEffect(() => { const provider = (window as any)?.phantom?.solana;

if (provider !== undefined) {
  provider.on("accountChanged", async () => {
    try {
      dispatch(setOverlapLoader(true));
      await wallet.disconnect();
      dispatch(logoutUser());
    } catch (error) {
      console.log("error", error);
    } finally {
      dispatch(setOverlapLoader(false));
    }
  });
}

}, [dispatch, wallet]);

1 Answer 1

0

Phantom itself does not expose any account-switching specific API on their window object.

For that, you have to continuously check the poll for the currently connected account and set the publicKey to variable or cookies. When the publicKey changes to current then you can trigger your event or functions.

Here are detailed answers for all the wallets.

let currentKey = '';

poll(() => {
  if (/* wallet available and connected */) {
    await /* Action that updates publicKey */
    if (currentKey !== wallet.publicKey.toBase58()) {
      currentKey = wallet.publicKey.toBase58();
      this.publicKey = wallet.publicKey;
      this.emit('change')
    }
  }
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.