How to Unsubscribe OnAccountsChanged event in react

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

@cryptokid Can you explain this little bit more?

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]);
1 Like