Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: network switch listen only once
- Loading branch information
simodrws
committed
Aug 11, 2023
1 parent
ed3dc56
commit 7c50d00
Showing
3 changed files
with
84 additions
and
32 deletions.
There are no files selected for viewing
40 changes: 40 additions & 0 deletions
40
src/refactor/wallet-client/network/use-network-switch-listen.ts
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import type { Connector, Provider } from '@wagmi/core'; | ||
import { useEffect } from 'react'; | ||
|
||
export const useNetworkSwitchListen = ({ | ||
activeConnector, | ||
stopSwitching, | ||
networkError, | ||
}: { | ||
activeConnector?: Connector | undefined; | ||
stopSwitching: () => void; | ||
networkError: Error | null; | ||
}) => { | ||
useEffect(() => { | ||
if (!activeConnector) { | ||
return undefined; | ||
} | ||
|
||
let provider: Provider; | ||
|
||
activeConnector | ||
?.getProvider?.() | ||
.then((provider_: Provider) => { | ||
provider = provider_; | ||
provider.on('chainChanged', stopSwitching); | ||
}) | ||
.catch((error: unknown) => { | ||
console.log("error getting provider's chainChanged event", error); | ||
}); | ||
|
||
return () => { | ||
provider?.removeListener('chainChanged', stopSwitching); | ||
}; | ||
}, [activeConnector, stopSwitching]); | ||
|
||
useEffect(() => { | ||
if (networkError && networkError.name === 'UserRejectedRequestError') { | ||
stopSwitching(); | ||
} | ||
}, [networkError, stopSwitching]); | ||
}; |
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
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