I have two modules
App.jsx
import React from 'react';
import ReactDOM from 'react-dom';
import {accounts} from './contract.jsx';
class App extends React.Component{
constructor(props){
super(props);
this.state={'text':'','accounts':'','clicked':false};
}
componentDidMount = () => {
this.setState({'accounts':accounts()});
}
buttonAction = (e) => {
this.setState({'clicked':true});
}
render(){
return(
<div align="center">
<Button name="get all Accounts" action={this.buttonAction}/>
{this.state.clicked ? <div>{this.state.accounts}</div> : null}
</div>
)}
}
const Button = (props) =>
(<button onClick={props.action}>{props.name}</button>);
ReactDOM.render(<App/>,document.getElementById('root'));
and contract.jsx
import Web3 from 'web3';
var web3 = new Web3(Web3.givenProvider || 'http://localhost:8545');
let accounts = () => {
// this is a promise
web3.eth.getAccounts().then(function(result){console.log(result);})
.catch(function(error){console.log(error.message)})
}
export {accounts};
I'm exporting accounts
(a promise) function from contract.jsx
to app.jsx
. Since I can't return value from a promise, I need to assign the value to the state of App
component inside the promise (check componentDidMount
). For that, I need to replace 'console.log(result)' in accounts
function to 'this.setState({'accounts':result})'. But the component and accounts
are in different modules and supposed to be independent. I cannot set the state of the App
component inside my accounts
function.
How can I assign the value from the promise to my state inside App
component? Is there any other better way to do it? I could also use some code corrections to make my component work better.