Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Unsubscribe all events #15

Merged
merged 5 commits into from Jul 27, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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