Uniswap / web3-react

A simple, maximally extensible, dependency minimized framework for building modern Ethereum dApps
https://web3-react-mu.vercel.app/
GNU General Public License v3.0
5.56k stars 1.52k forks source link

WalleConnectV2 deactivate #940

Open supermars01 opened 4 months ago

supermars01 commented 4 months ago

How do I disconnect WalleConnectV2 when I refresh the page? Or how to maintain connectivity? Can anyone help me.

m-Jawa-d commented 3 months ago

To handle disconnecting WalletConnectV2 on page refresh or maintaining connectivity across refreshes, you can follow these steps:

Disconnecting WalletConnectV2 on Page Refresh

To disconnect WalletConnectV2 when the page is refreshed, you can listen for the beforeunload event and call the disconnect method on the WalletConnectV2 instance. Here’s an example:

import { useWeb3React } from '@web3-react/core';

function App() {
  const { connector } = useWeb3React();

  useEffect(() => {
    const handleBeforeUnload = () => {
      if (connector?.deactivate) {
        connector.deactivate();  // Ensure WalletConnect is deactivated on refresh
      }
    };

    window.addEventListener('beforeunload', handleBeforeUnload);

    return () => {
      window.removeEventListener('beforeunload', handleBeforeUnload);
    };
  }, [connector]);

  return (
    // Your application code here
  );
}

This code ensures that WalletConnectV2 disconnects when the user refreshes the page.

Maintaining Connectivity Across Refreshes

To maintain connectivity after a page refresh, you need to save the connection state and restore it on page load. Here’s how you can implement this:

1. Store the Connection State: Save the WalletConnect session to localStorage when the user connects.

import { useWeb3React } from '@web3-react/core';

function App() {
  const { connector, activate } = useWeb3React();

  useEffect(() => {
    if (connector?.walletConnectProvider?.wc) {
      const session = connector.walletConnectProvider.wc.session;
      localStorage.setItem('walletConnectSession', JSON.stringify(session));
    }
  }, [connector]);

  return (
    // Your application code here
  );
}

2. Reconnect on Page Load:

On page load, check for an existing session in localStorage and reconnect using that session.

import { useWeb3React } from '@web3-react/core';
import { WalletConnectConnector } from '@web3-react/walletconnect-v2';

function App() {
  const { activate } = useWeb3React();

  useEffect(() => {
    const savedSession = JSON.parse(localStorage.getItem('walletConnectSession'));

    if (savedSession) {
      const walletConnect = new WalletConnectConnector({
        session: savedSession,
        // Add other configuration options as needed
      });

      activate(walletConnect);
    }
  }, [activate]);

  return (
    // Your application code here
  );
}