1
0
mirror of https://github.com/kremalicious/blog.git synced 2024-12-22 09:13:35 +01:00

web3 detection improvements

This commit is contained in:
Matthias Kretschmann 2018-10-11 20:06:02 +02:00
parent 2e85f7e24b
commit 0ca1e977cd
Signed by: m
GPG Key ID: 606EEEF3C479A91F
2 changed files with 72 additions and 77 deletions

View File

@ -35,6 +35,7 @@ export default class PostActions extends PureComponent {
>
@kremalicious
</a>
.
</p>
</article>
<article className={styles.action}>

View File

@ -22,14 +22,16 @@ export default class Web3Donation extends PureComponent {
address: PropTypes.string
}
web3 = new Web3(Web3.givenProvider || 'ws://localhost:8546')
web3 = null
interval = null
networkInterval = null
componentDidMount() {
const { web3 } = this
if (web3 && web3.eth) {
if (typeof window.web3 === 'undefined') {
// no web3
this.setState({ web3Connected: false })
} else {
this.web3 = new Web3(Web3.givenProvider || 'ws://localhost:8546')
this.setState({ web3Connected: true })
this.fetchAccounts()
@ -64,17 +66,15 @@ export default class Web3Donation extends PureComponent {
web3.eth &&
web3.eth.net.getId((err, netId) => {
if (err) {
this.setState({
networkError: err
})
} else {
this.setState({ networkError: err })
}
if (netId != this.state.networkId) {
this.setState({
networkError: null,
networkId: netId
})
}
}
})
}
@ -85,15 +85,13 @@ export default class Web3Donation extends PureComponent {
web3.eth &&
web3.eth.getAccounts((err, accounts) => {
if (err) {
this.setState({
accountsError: err
})
} else {
this.setState({ accountsError: err })
}
this.setState({
accounts,
selectedAccount: accounts[0]
})
}
})
}
@ -117,13 +115,12 @@ export default class Web3Donation extends PureComponent {
}
render() {
if (this.state.web3Connected) {
return (
<div className={styles.web3}>
<h4>web3</h4>
<p>Send a donation with your MetaMask or Mist account.</p>
<p>Send a donation with MetaMask or Mist.</p>
{this.state.web3Connected && (
{this.state.web3Connected ? (
<div>
{this.state.loading ? (
'Hang on...'
@ -141,15 +138,13 @@ export default class Web3Donation extends PureComponent {
{this.state.accounts.length === 0 && (
<div className={styles.alert}>
Web3 detected, but no account. Are you logged into your
MetaMask account?
Web3 detected, but no account. Are you logged into your MetaMask
account?
</div>
)}
{this.state.networkId !== 1 && (
<div className={styles.alert}>
Please connect to Main network
</div>
<div className={styles.alert}>Please connect to Main network</div>
)}
{this.state.error && (
@ -170,11 +165,10 @@ export default class Web3Donation extends PureComponent {
</div>
)}
</div>
) : (
<div className={styles.alert}>No Web3 capable browser detected.</div>
)}
</div>
)
} else {
return null
}
}
}