perawallet / connect-examples

Example applications for `@perawallet/connect`
https://github.com/perawallet/connect
Apache License 2.0
3 stars 2 forks source link

Syntax Conventions #2

Closed Bhaney44 closed 2 years ago

Bhaney44 commented 2 years ago

This Issue relates to this example file. The issues are discussed in comments.

import { useState, useEffect } from "react";
import { PeraWalletConnect } from "@perawallet/connect";

import "./styles.css";

const peraWallet = new PeraWalletConnect();

export default function App() {
  const [accountAddress, setAccountAddress] = useState(null);
  const isConnectedToPeraWallet = !!accountAddress;

/// In this function it is unclear whether a connect or disconnect is happening because of the syntax:
/// peraWallet.connector.on("disconnect", handleDisconnectWalletClick);

  useEffect(() => {
    // Reconnect to the session when the component is mounted
    peraWallet
      .reconnectSession()
      .then((accounts) => {
        peraWallet.connector.on("disconnect", handleDisconnectWalletClick);
        if (accounts.length) {
          setAccountAddress(accounts[0]);
        }
      })
      .catch((e) => console.log(e));
  }, []);

  return (
    <button
      onClick={
        isConnectedToPeraWallet
          ? handleDisconnectWalletClick
          : handleConnectWalletClick
      }
    >
      {isConnectedToPeraWallet ? "Disconnect" : "Connect to Pera Wallet"}
    </button>
  );

  function handleConnectWalletClick() {
    peraWallet
      .connect()
      .then((newAccounts) => {
        peraWallet.connector.on("disconnect", handleDisconnectWalletClick);
        setAccountAddress(newAccounts[0]);
      })
      .catch((error) => {
        if (error?.data?.type !== "CONNECT_MODAL_CLOSED") {
          console.log(error);
        }
      });
  }

  function handleDisconnectWalletClick() {
    peraWallet.disconnect();
    setAccountAddress(null);
  }
}

Ultimately, in an ideal situation, there would be only two functions.

function WalletConnect {
}
function WalletDisconnect{
}

The complexities in the current methodologies are causing user errors in several applications. I'm wondering how we can reduce these example to have a clear and concise function for both connect and disconnect.

Bhaney44 commented 2 years ago

Solved (PR).