This method is not working, I need to unsubscribe the OnAccountsChanged event #reactmoralis
itโs onAccountChanged
and if you donโt need it anymore you can simply delete the code
Thank you @YosephKS for the reply, But here is my problem, I need onAccountChanged
event for my webapp to identify the account changing event of MetaMask
. But I need this event only when user logged into the app. When user logging out, need to unsubscribe the event. Therefore, when the user is not logged in, no need to trigger the onAccountChanged
event.
you can try to subscribe again with another function that doesnโt do anything
I was thinking that if you try to subscribe again, the previous subscription will be removed
A new call of onAccountChanged(โฆ) adds a new listener every time until the limit is reached (default: 5) but it also returns the EventEmitter which can be used to unsubscibe. I use it this way:
useEffect(() => {
const eventEmitter = onAccountChanged(() => {
if (isAuthenticated) {
logout();
message.warn(
"You changed your account in your wallet app. Please login again with the new account."
);
}
});
return () => {
eventEmitter().removeAllListeners();
};
}, [isAuthenticated, logout, onAccountChanged]);