[Ethereum] How to keep MetaMask connection to the UI persistent with Web3-react

metamaskreactweb3js

I am working with web3-react and I cannot figure out how to keep the connection to the MetaMask wallet persistent upon browser refreshes.

This is the code:

// define the injectedConnectors

const injectedConnector = new InjectedConnector({
  supportedChainIds: [
    1, // Mainet
    3, // Ropsten
    4, // Rinkeby
    5, // Goerli
    42, // Kovan
  ],
})

const { chainId, account, activate, active } = useWeb3React()
// activate the wallet
activate(injectedConnector)
console.log(account)
// all good. 

Up to here all is working and I activate my MetaMask wallet as well as I get the account correctly logged, and the active variable is a boolean that changes to true.
The problem is that when I refresh the page the active turns to false and I lose the connection between the UI to the MetaMask wallet. Of course saving active into the browser does not change anything because the connection relies on the active boolean value.
The docs are lacking such information.
Any help would be gladly appreciated.

Best Answer

It is called 'Eager connect'

  • Store the connectorId in your local storage
  • On page load, use that key to call activate from '@web3-react/core'

-> the account should be updated.

Reference: https://github.com/pancakeswap/pancake-frontend/blob/develop/src/hooks/useEagerConnect.ts

Related Topic