Skip to content

Instantly share code, notes, and snippets.

@ibelick
Created February 14, 2022 14:56
Show Gist options
  • Save ibelick/7545ab50dcc86a4d8afc46ef67762ee2 to your computer and use it in GitHub Desktop.
Save ibelick/7545ab50dcc86a4d8afc46ef67762ee2 to your computer and use it in GitHub Desktop.
Simple connect to MetaMask with React + TypeScript
const ButtonConnectWallet: React.FC = () => {
const [address, setAddress] = useState<string | null>(null);
const connectWallet = async () => {
if (!window?.ethereum) {
alert("No wallet found. Please install MetaMask.");
return;
}
try {
const accounts = await window.ethereum.request<string[]>({
method: "eth_requestAccounts",
});
if (accounts.length === 0) {
alert("No authorized account found");
}
setAddress(accounts[0]);
} catch (error) {
console.error("error", error);
}
};
useEffect(() => {
if (
typeof window.ethereum !== "undefined" &&
typeof window.ethereum.selectedAddress == "string"
) {
setAddress(window.ethereum.selectedAddress);
}
}, []);
useEffect(() => {
if (!window?.ethereum) {
return;
}
const listener = ([selectedAddress]: string[]) => {
setAddress(selectedAddress);
};
window.ethereum.on("accountsChanged", listener);
return () => {
window.ethereum.removeListener("accountsChanged", listener);
};
}, []);
return (
<button onClick={connectWallet}>
{address ? truncateEthAddress(address) : `Connect Wallet`}
</button>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment