Reputation: 353
I'm creating a DEFI dapp, I want to get the account that is connected with the meta mask using web3.eth.get accounts();
This is what I got when console.log ['0x32F36b36e78E89bdd6efa9e893ec2d87e4E2e3E9'], I've created use State to push this account to use in React components as props but when I console.log the value of useState I got nothing.
Then if I will get this value inside useState how can I pass it into the balanceOf function?
useState
const [userAccount, setUserAccount] = useState([]);
the function to get the accounts and get the balance of this account
const blockchainDataLoad = async () => {
const web3 = window.web3;
console.log(userAccount);
// get the Accounts
const accounts = await web3.eth.getAccounts();
setUserAccount(accounts[0]);
// get the Network Id of The contracts
const networkId = await web3.eth.net.getId();
// ******************************** Dai Token EuroToken ************************* //
// Get the deployed contract object using the network ID
const daiTokenData = DaiToken.networks[networkId];
if(daiTokenData) {
// Create a instance of the contract
const daiToken = new web3.eth.Contract(DaiToken.abi, daiTokenData.address);
setDTokens(daiToken);
// get the balance from the investor account
**let daiTokenBalance = await daiToken.methods.balanceOf(userAccount).call();**
setDTokenBalance(daiTokenBalance.toString());
console.log(daiTokenBalance);
Upvotes: 1
Views: 492
Reputation: 49681
You should get the accounts in useEffect
hook, so when your component renders, your component's state will be already set.
useEffect(() => {
const getAccount = async () => {
const accounts = await web3.eth.getAccounts();
setAccount(accounts[0]);
};
// call getAccount() if web3 is defined otherwise you app will break
web3 && getAccount();
}, [web3]);
Upvotes: 1