1

I have a 'connect wallet' button to allow users to connect and disconnect at will. If I connect and then reload, however, the connection reverts to 'disconnected'. In other words, the connection is not persistent between reloads. How can I make it persistent?

export function ConnectButton() {
  const [account, setAccount] = useState('');

  async function connectPrompt() {
    const provider = await web3Modal.connect();
    const web3 = new Web3(provider);
    const firstAccount = await web3.eth.getAccounts().then(data=>data[0]);
    setAccount(firstAccount);
  }

  async function disconnect() {
    await web3Modal.clearCachedProvider();
    setAccount('')
  }
  
  const providerOptions = {};
  const web3Modal = new Web3Modal({
    network: "mainnet", 
    cacheProvider: true,
    providerOptions // required
  });

  return (
           {account == '' ? <button onClick={()=>connectPrompt()}>Connect</button> : 
           <button onClick={()=>disconnect()}>Disconnect</button>}
  )
}
1
  • I would like to know the same thing. I'll update here if I find out how to persist a wallet connection.
    – Dawson B
    Oct 21, 2021 at 20:28

1 Answer 1

1

The connection does not actually gets disconected on reload. If you check metamask, the connection is still active. It is your account state variable that gets set to empty string (default value to useState()) hence the connect button shows again. To make it persistent is to add a useEffect hook and call the connect method once on every load. You can simply check that WEB3_CONNECT_CACHED_PROVIDER is set in the localStorage and call the connect button if the value is true. See below

const [account, setAccount] = useState('');

useEffect(() => {
  (async () => {
     if(localStorage.getItem("WEB3_CONNECT_CACHED_PROVIDER")) await connectPrompt();
  })()
}, [])

async function connectPrompt() {
  const provider = await web3Modal.connect();
  const web3 = new Web3(provider);
  const firstAccount = await web3.eth.getAccounts().then(data=>data[0]);
  setAccount(firstAccount);
}

async function disconnect() {
  await web3Modal.clearCachedProvider();
  setAccount('')
}

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

return (
         {account == '' ? <button onClick={()=>connectPrompt()}>Connect</button> : 
         <button onClick={()=>disconnect()}>Disconnect</button>}
)
} 

Note that web3modal automatically sets WEB3_CONNECT_CACHED_PROVIDER to the local storage and is based on the cacheProvider passed to the providerOptions object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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