As someone who has previously worked with the @web-react/core legacy version 6.1.9, I understand how daunting it can be to update to the latest version, 8.2.0. However, as I have just started a new freelance job and discovered that they are using the latest version, I see the importance of familiarizing myself with the new syntax. In this article, I want to share my experience of updating to @web-react/core v8.2.0 and guide you through the changes in syntax and functionality. By the end of this article, you will have a better understanding of the new updates and be able to use @web-react/core v8.2.0 confidently in your projects.
Before we dive into the changes in syntax and functionality, let's make sure we have all of the necessary packages installed. To do this, we can run the following command in our terminal
npm i web3 @web3-react/core @web3-react/metamask
This command installs the web3 library, which is the Ethereum JavaScript API, as well as the @web3-react/core
and @web3-react/metamask
packages. The @web3-react/core
package is the main package for connecting to the Ethereum network using Web3, while the @web3-react/metamask
package provides a connector specifically for the MetaMask wallet.
To start using the @web3-react/metamask package, we need to create a connector for it. To do this, we can create a new folder called connectors
inside the src
folder of our project. Then, inside the connectors
folder, we can create a new file called metaMask.ts
with the following content
import { initializeConnector } from '@web3-react/core'
import { MetaMask } from '@web3-react/metamask'
export const [metaMask, useMetaMask] = initializeConnector<MetaMask>(
(actions) => new MetaMask({ actions })
)
We are then using the initializeConnector
function to create a connector called metaMask
for the MetaMask wallet. We are also using the useMetaMask
hook, which allows us to access the current account and provider for the MetaMask wallet.
We need to export that connector so we can use it throughout our application. To do this, we can create a new file called index.ts
inside the connectors
folder and export the connector
import { Web3ReactHooks } from '@web3-react/core'
import { MetaMask } from '@web3-react/metamask'
import { metaMask, useMetaMask } from './metaMask'
export const connectors: [MetaMask, Web3ReactHooks][] = [[metaMask, useMetaMask]]
Now that we have created and exported our connector, we need to use it to set up the Web3Provider in our application. To do this, we can go to our App.tsx
file and import the Web3ReactProvider
component from the @web3-react/core package. We can then use this component to create our provider with the connectors
array we exported earlier.
Here is an example of how to create the provider in the App.tsx
file
import { Web3ReactProvider } from '@web3-react/core'
import { connectors } from './connectors'
function App() {
return (
<Web3ReactProvider connectors={connectors}>
{/* Your app code goes here */}
</Web3ReactProvider>
)
}
In this code, we are using the Web3ReactProvider
component to create our provider and passing in the connectors
array as a prop. We are also wrapping our entire application with the provider, which enables us to access the current account and provider for the MetaMask wallet throughout our application.
Now that we have set up the provider for @web-react v8.2.0 with the MetaMask wallet, we can create a component that allows users to connect their MetaMask wallet to our application.
import { useEffect, useState } from "react";
import { useWeb3React } from "@web3-react/core";
import Web3 from "web3";
export const MetaMaskBtn = () => {
const [loading, setLoading] = useState(false)
…
const onConnectMetaMask = async () => {
const chainId = process.env.SUPPORT_CHAIN_ID || "5";
try {
if (
chainId &&
window.ethereum &&
window.ethereum.networkVersion !== chainId
) {
try {
await window.ethereum.request({
method: "wallet_switchEthereumChain",
params: [{ chainId: Web3.utils.toHex(parseInt(chainId)) }],
});
} catch (err: any) {
console.log("Network changed rejected", err);
}
} else {
setLoading(true);
try {
await connector.activate(chainId);
} catch (err) {
console.log("User rejected the request", err);
setLoading(false);
}
}
} catch (error) {
console.log(error);
}
};
return (
{/* Your html code goes here */}
)
}
This function checks the current chain ID and network version of the MetaMask wallet, and either switches to the correct network or activates the connector if it's already on the correct network.
There's no need to worry about including HTML code in the remaining sections of this article. To make it even easier, I will attach my demo repository URL at the end of the article so you can see the full code and test it out for yourself.
To complete the functionality of our MetaMask connector component, we also need to create a function that allows users to disconnect their MetaMask wallet from our application.
const onDisconnectMetaMask = () => {
if (connector?.deactivate) {
connector.deactivate()
} else {
connector.resetState()
}
}
While some kinds of connectors will provide a deactivate
function to disconnect the wallet, others may not. In those cases, we can simply call the resetState
function from @web3-react/core to reset all states related to the connector.
By calling resetState
, we ensure that all cached values and event listeners related to the connector are cleared, allowing us to safely switch to a different connector or reset the current connector's state.
We hope that this article has been helpful in guiding you through the process of using @web3-react v8.2.0 with the MetaMask wallet in your React application. Thank you for reading, and we wish you the best of luck in your blockchain development endeavors.
The repository with all code is here: https://github.com/mike-yuen/web3-react-connector