My React Minting Dapp is for Avalanche. I have implemented safeguards for βUser on Wrong Network (wrong chain)β simply using the useChain() hook in the following manner:
In my App.jsx
:
const { switchNetwork, chainId, chain } = useChain();
useEffect(() => {
const connectorId = window.localStorage.getItem("connectorId");
if (isAuthenticated && !isWeb3Enabled && !isWeb3EnableLoading){
enableWeb3({ provider: connectorId });}
if (chainId != '0xa86a') {
if (window.confirm("You're on the wrong network! Click OK to switch to Avalanche C-chain!")) {
switchNetwork("0xa86a")
} else {
alert("You're on the wrong network & will result in loss of funds due to failed transaction!
Switch to Avalance C-chain manually in your Metamask Wallet!");
}
}
}, [isAuthenticated, isWeb3Enabled, chain]);
This way, while logging in if the user is on any network other than Avalanche c-chain, a pop-up appears, and on clicking **ok**
the Moralis switchNetwork
function switches metamask to Avalanche chain. On clicking cancel a second warning appears. Same if the user switches networks mid-way after logging in for any reason.
Similarly,
I am using const { account } = useMoralis();
to handle any user account switches. The user address displayed in my navbar + all traits obtained from the wallet immediately change automatically when user switches from one account to another.
My question is: Is there any negative side to my method? I see almost everyone else uses event listeners in their React dapps to handle these things. However my app responds to the above changes and handles them flawlessly without event listeners. Am I missing something?