web3-react icon indicating copy to clipboard operation
web3-react copied to clipboard

WalleConnectV2 deactivate

Open supermars01 opened this issue 1 year ago • 1 comments

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

supermars01 avatar Jul 09 '24 01:07 supermars01

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
  );
}

m-Jawa-d avatar Aug 13 '24 13:08 m-Jawa-d