Skip to content

Instantly share code, notes, and snippets.

@o-az
Created February 19, 2022 06:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save o-az/a7e490c964957d5fcf47d9248ee402ca to your computer and use it in GitHub Desktop.
Save o-az/a7e490c964957d5fcf47d9248ee402ca to your computer and use it in GitHub Desktop.
a react custom hook to detect account change and do things
import * as React from 'react';
import { providers } from 'ethers';
const logout = async () =>
axios
.get('/api/auth/logout')
.then(_ => _)
.catch(_ => console.log(_));
export const useDetectAccountChange = () => {
return React.useEffect(() => {
if (typeof window.ethereum?.on === 'undefined') return;
const provider = new providers.Web3Provider(window.ethereum as any);
provider
.getSigner()
.getAddress()
.then(address => {
(window.ethereum as any).on('accountsChanged', (accounts: string[]) => {
const [, newAddress] = accounts;
if (newAddress !== address) {
// do stuff here, for example: window.location.reload()
// I'm clearing user cookie and logging then out on account change
logout();
}
});
});
}, []);
};
// then, in your main 'App' or '_app' or 'index' file, import the hook:
// App.tsx
import { useDetectAccountChange } from './path'
export default function App() {
useDetectAccountChange();
return (
<div>
stuff
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment