Was recently making a project using Moralis where I used it for user Auth.
When implemented I want when a user is inside app, and if user switches his account the address should update on app as well. So on going through docs I found onAccountChanged() for that. It works fine but causing Memory leak warning.
const Dashboard = () => {
const { Moralis, isAuthenticated, user, logout } = useMoralis();
const [userAddress, setUserAddress] = useState();
const router = useRouter();
const handleLogout = async () => {
await logout();
console.log("logged out");
};
// UseEffect with onAccountChanged() causing Memory Leak -------------
useEffect(() => {
// Account switching
Moralis.onAccountChanged(async (chain) => {
console.log("Account changed to:", chain);
setUserAddress(chain);
});
}, [Moralis]);
useEffect(() => {
if (!isAuthenticated) router.replace("/");
setUserAddress(user?.get("ethAddress"));
}, [isAuthenticated, router, user]);
return (
<div>
<h2>
Logged in as {userAddress?.slice(0, 6)}...{userAddress?.slice(39)}
</h2>
<button onClick={handleLogout}>Logout</button>
<Link href="/game">
<a>Start Game!</a>
</Link>
</div>
);
};
export default Dashboard;