Skip to content

Commit

Permalink
Only emit state change events after initialization (#117)
Browse files Browse the repository at this point in the history
It was reported in #110 that `chainChanged` (and by extension, `networkChanged`) is sometimes emitted for the first time after page load, causing a reload loop for those handling chain changes by reloading the page. When the `chainId` is set on initialization, the chain has not changed, and `chainChanged` should not be emitted. The same can be said for `accountsChanged`, which currently would emit under the same circumstances.

This PR ensures that `chainChanged`, `networkChanged`, and `accountsChanged` are only emitted after the provider has been initialized.
  • Loading branch information
rekmarks authored Dec 7, 2020
1 parent 625f6fa commit 965001e
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions src/MetaMaskInpageProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -482,12 +482,16 @@ module.exports = class MetaMaskInpageProvider extends SafeEventEmitter {

if (chainId !== this.chainId) {
this.chainId = chainId
this.emit('chainChanged', this.chainId)
if (this._state.initialized) {
this.emit('chainChanged', this.chainId)
}
}

if (networkVersion !== this.networkVersion) {
this.networkVersion = networkVersion
this.emit('networkChanged', this.networkVersion)
if (this._state.initialized) {
this.emit('networkChanged', this.networkVersion)
}
}
}
}
Expand Down Expand Up @@ -532,8 +536,10 @@ module.exports = class MetaMaskInpageProvider extends SafeEventEmitter {
this.selectedAddress = _accounts[0] || null
}

// only emit the event once all state has been updated
this.emit('accountsChanged', _accounts)
// finally, after all state has been updated, emit the event
if (this._state.initialized) {
this.emit('accountsChanged', _accounts)
}
}
}

Expand Down

0 comments on commit 965001e

Please sign in to comment.