[Ethereum] How to disconnect MetaMask wallet using Web3modal

reactweb3js

I am using metamask with kovan to connect to the wallet 
import React, { useState, useEffect} from 'react';
import Web3 from "web3";
import Web3Modal from "web3modal";
import Navbar from './components/navbar';

function App() {
const providerOptions = {};
const web3Modal = new Web3Modal({
  network: "mainnet", // optional
  cacheProvider: true, // optional
  providerOptions // required
});

  const [account, setAccount] = useState('');
  async function connect() {
    try {
      const provider = await web3Modal.connect();
      const web3 = new Web3(provider);
      const accounts = await web3.eth.getAccounts();
      setAccount(accounts[0]);
    } catch (err) {
      console.error(err);
    }
  }


  useEffect(() => {
    if (window.web3) {
      connect();
    }
  }, []);

   async function disconnect() {
    const clear = await web3Modal.clearCachedProvider();
  }

  return (
    <div>
     <Navbar account={account} connect={connect} disconnect={disconnect} />
    </div>
  );
}

export default App;

how do i disconnect from the metamask?

Best Answer

It's not possible.

The connect/disconnect functionality is entirely in the user's hands due to security and privacy concerns.

You can only pretend a disconnect by resetting a provider, chainId and selectedAccount to null and clearing the cache of the provided you previously used.

P.S.: I know this is a harsh reality. Upvote this as it's the only correct answer that there is! You have to pretend from your app that the user has disconnected. This is the way I do it in my dapp, the way PancakeSwap does, Uniswap too, etc...

Related Topic