简体   繁体   中英

cannot disconnect or close or clear accounts from web3model or web3

I am trying to disconnect from the provider so that I can show a screen with a button to connect when not connected and show a display screen when already connected.

the example code doesn't work:

public resetApp = async () => {
    const { web3 } = this.state;
    if (web3 && web3.currentProvider && web3.currentProvider.close) {
      await web3.currentProvider.close();
    }
    await this.web3Modal.clearCachedProvider();
    this.setState({ ...INITIAL_STATE });
  };

web3.currentProvider.close(); is not a function. the condition is never met. all examples on the web doesn't work.

this code below always returns an address and nothing ive tried has cleared it except for manual disabling metamask and enable it again from the chrome extension settings.

      const accounts = await web3.eth.getAccounts();
      if (accounts[0] != null) {
          // connected
          resolve(true);
      } else {
          // not connected
          resolve(false);
      }

Please can anyone assist.

Found the solution: My condition was testing the wrong thing (not sure how else to say it). If you call await web3Modal.clearCachedProvider(); then web3Modal.cachedProvider returns an empty string.

// test if wallet is connected
if (web3Modal.cachedProvider) {
    // connected now you can get accounts
    const accounts = await web3.eth.getAccounts();
}

// disconnect wallet
const disconnectWallet = async (web3Modal: any) => {
    await web3Modal.clearCachedProvider();
}

This will work;

async onDisconnect() {
  await web3Modal.clearCachedProvider();
  window.localStorage.clear();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM