Created
February 19, 2022 06:44
-
-
Save o-az/a7e490c964957d5fcf47d9248ee402ca to your computer and use it in GitHub Desktop.
a react custom hook to detect account change and do things
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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