1

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.

1 Answer 1

1

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!

3
  • I'll check it right now! Thanks!
    – OhItsPM
    Apr 12 at 0:14
  • That worked! Amazing how something so simple could work that well
    – OhItsPM
    Apr 12 at 0:17
  • Thks, please can you vote for the answer and mark the question as solved? That would help others looking for the same problem.
    – donoso.eth
    Apr 12 at 5:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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