Skip to content

Commit

Permalink
Merge pull request #15 from byterose/patch-1
Browse files Browse the repository at this point in the history
Unsubscribe all events
  • Loading branch information
clbrge authored Jul 27, 2021
2 parents 9b2faed + 9babef3 commit beed29a
Showing 1 changed file with 19 additions and 18 deletions.
37 changes: 19 additions & 18 deletions src/web3-store.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,28 +41,29 @@ 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))
} else {
if (instance._provider && instance._provider.on) {
instance._provider.on('accountsChanged', () => setProvider(provider, true))
instance._provider.on('chainChanged', () => setProvider(provider, true))
}
})
}
update(() => ({
provider,
providerType: 'String',
connected: true,
chainId,
accounts,
instance
}))
}

const setBrowserProvider = async () => {
Expand All @@ -82,8 +83,8 @@ export const createStore = () => {
}

const close = async (provider) => {
if(provider && provider.close) {
await provider.close()
if(provider && provider.disconnect) {
await provider.disconnect()
}
update(() => ({
connected: false,
Expand Down

0 comments on commit beed29a

Please sign in to comment.