Skip to content

Commit

Permalink
Unsubscribe all events
Browse files Browse the repository at this point in the history
__networkChanged__ will emit the network ID as a decimal string
__chainChanged__ will emit the chain ID as a hexadecimal string

I commented out the __chainChanged__ listener since only one chain / network listener is needed.
  • Loading branch information
byterose authored Jul 26, 2021
1 parent 9b2faed commit cd54e39
Showing 1 changed file with 19 additions and 16 deletions.
35 changes: 19 additions & 16 deletions src/web3-store.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,28 +41,31 @@ export const createStore = () => {
if (getWindowEthereum()) getWindowEthereum().autoRefreshOnNetworkChange = false
}

const setProvider = async provider => {
const setProvider = async (provider, callback?) => {
init()
const instance = new Web3(provider)
const chainId = await instance.eth.getChainId()
// no account with ganache
const accounts = /127/.test(provider) ? [] : await instance.eth.getAccounts()
if (instance._provider && instance._provider.on) {
instance._provider.on('accountsChanged', () => setProvider(provider))
instance._provider.on('chainChanged', () => setProvider(provider))
instance._provider.on('networkChanged', () => setProvider(provider))
}
update(previous => {
// TODO if (previous.instance) unsubcribe all events
return {
provider,
providerType: 'String',
connected: true,
chainId,
accounts,
instance,
if (callback) {
instance._provider.removeListener('accountsChanged', () => setProvider(provider, true))
// instance._provider.removeListener('chainChanged', () => setProvider(provider, true))
instance._provider.removeListener('networkChanged', () => setProvider(provider, true))
} else {
if (instance._provider && instance._provider.on) {
instance._provider.on('accountsChanged', () => setProvider(provider, true))
// instance._provider.on('chainChanged', () => setProvider(provider, true))
instance._provider.on('networkChanged', () => setProvider(provider, true))
}
})
}
update(() => ({
provider,
providerType: 'String',
connected: true,
chainId,
accounts,
instance
}))
}

const setBrowserProvider = async () => {
Expand Down

0 comments on commit cd54e39

Please sign in to comment.