@rc_plt hello again )
When initializing the application, you need to determine the current web3 provider and a web3 instance:
useEffect(() => {
const loadProvider = async () => {
const provider = await detectEthereumProvider()
if (provider) {
const web3 = new Web3(provider);
setListener(provider);
setApi({
provider,
web3
});
} else {
console.error("gotta be install metamask");
}
};
loadProvider();
}, []);
The listener function will help you with automatic page reloading in case of network switch in MetaMask:
const setListener = provider => {
provider.on("chainChanged", _ => window.location.reload());
};
Next, you must pass the value set in setApi to the entire application (memoize this to improve performance!), For example, through the context or a convenient state manager for you.
Just for example:
<Web3.Provider value={Api}>{your application}</Web3.Provider>