Skip to content

Commit

Permalink
Add onChangeAccount callback and selectedAccount context variable
Browse files Browse the repository at this point in the history
  • Loading branch information
fvictorio committed Mar 12, 2018
1 parent 329d5d1 commit 9eb190f
Showing 1 changed file with 68 additions and 4 deletions.
72 changes: 68 additions & 4 deletions src/react-web3/Web3Provider.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,88 @@
import React, { Component } from 'react';
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import Web3 from 'web3'

const ONE_SECOND = 1000;

class Web3Provider extends Component {
constructor(props, context) {
super(props, context)

this.state = {
selectedAccount: null
}

this.web3 = null
this.interval = null

}
render() {
const { web3UnavailableScreen: Web3UnavailableScreen } = this.props

if (window.web3) {
if (!this.web3) {
this.web3 = new Web3(window.web3.currentProvider);
this.fetchAccounts()
}

return this.props.children
}

return <this.props.web3UnavailableScreen />
return <Web3UnavailableScreen />
}

componentDidMount() {
this.initPoll();
}

initPoll = () => {
if (!this.interval) {
this.interval = setInterval(this.fetchAccounts, ONE_SECOND)
}
}

fetchAccounts = () => {
const { web3 } = this
const { onChangeAccount } = this.props

if (!web3 || !web3.eth) {
return
}

return web3.eth.getAccounts()
.then(accounts => {
if (!accounts || !accounts.length) {
return
}

let curr = this.state.selectedAccount
let next = accounts[0]
curr = curr && curr.toLowerCase()
next = next && next.toLowerCase()

const didChange = curr && next && (curr !== next)

if (didChange && typeof onChangeAccount === 'function') {
onChangeAccount(next)
}

this.setState({
selectedAccount: next || null
})
})
}

getChildContext() {
return {
web3: window.web3
web3: this.web3,
selectedAccount: this.state.selectedAccount
}
}
}

Web3Provider.childContextTypes = {
web3: PropTypes.object
web3: PropTypes.object,
selectedAccount: PropTypes.string
}

export default Web3Provider;

0 comments on commit 9eb190f

Please sign in to comment.