Ethersjs – How to Keep Wallet Connection Persistent When Refreshing with Ethersjs

dappsethers.jsmetamaskreactwallets

I am trying to figure out the best solution to keep a wallet connection persistent when a page refreshes on Ethers. So far, the only answers I've found have been through Web3-react and not Ethers.

Here is my context for getting the connect accounts, and I import the account state and connectWallet function into all components that need them to run transactions. Additionally, my provider is coming from a configs file that connects to an Alchemy provider:

import { createContext, useContext, useState } from "react";
import { provider } from "../utils/configs";

const WalletContext = createContext(null);

const WalletProvider = ({ children }) => {
  const [account, setAccount] = useState(null);
  const [signer, setSigner] = useState();

  function connectWallet() {
    try {
      window.ethereum.request({
        method: "eth_requestAccounts",
      });
      const signerAccount = provider.getSigner();
      setSigner(signerAccount);
      signerAccount.getAddress().then((address) => setAccount(address));
    } catch (error) {
      console.error("Error connecting to wallet", error);
      alert("Error connecting to wallet");
    }
  }

  const walletActions = { connectWallet };

  return (
    <WalletContext.Provider value={{ account, ...walletActions }}>
      {children}
    </WalletContext.Provider>
  );
};

const useWallet = () => useContext(WalletContext);

const useWalletActions = () => {
  const { connectWallet } = useWallet();

  return { connectWallet };
};

export { WalletProvider, useWallet, useWalletActions };

I've then wrapped the Provider around my App.js so the user only needs to log in once.

But when I refresh, I have to constantly log back in to gain a connection and that doesn't seem very user-friendly for the dApp.

Can anyone provide a short explanation on how I can keep the wallet connection persistent when refreshing? If so, is there a minimum amount of time when that connection stays persistent? Like if after 5 minutes, the account needs to be connected again.

Best Answer

have you tried to query "eth_accounts" inside a useEffect, I think this should work.

  useEffect(() => {
       
    window.ethereum.request({
    method: "eth_accounts",
  });
  const signerAccount = provider.getSigner();
  setSigner(signerAccount);
  signerAccount.getAddress().then((address) => setAccount(address));

  }, []);

Hope it helps!

Related Topic