I wrote an example Component that demonstrates the problem with both, the AccountData component, and the account information in drizzleState. I also provide a workaround using the web3 API directly.
import React, { useState, useEffect } from "react";
import { newContextComponents } from "@drizzle/react-components";
const { AccountData } = newContextComponents;
const AccountChangeDetection = ({ drizzle, drizzleState }) => {
const [ drizzleAcc, setDrizzleAcc ] = useState(drizzleState.accounts[0]);
const [ drizzleBal, setDrizzleBal ] = useState(drizzleState.accountBalances[drizzleState.accounts[0]]);
const [ web3Acc, setWeb3Acc ] = useState(null);
const [ web3Bal, setWeb3Bal ] = useState(null);
useEffect(() => {
function loadWeb3Data(web3) {
web3.eth.getAccounts()
.then( accounts => {
setWeb3Acc(accounts[0]);
web3.eth.getBalance(accounts[0])
.then(setWeb3Bal);
} );
}
async function listenMMAccount() {
window.ethereum.on("accountsChanged", async function () {
// console.log("Account changed");
// console.log(drizzleState.accountBalances[drizzleState.accounts[0]]);
setDrizzleAcc(drizzleState.accounts[0]);
setDrizzleBal(drizzleState.accountBalances[drizzleState.accounts[0]]);
loadWeb3Data(drizzle.web3);
});
}
loadWeb3Data(drizzle.web3);
listenMMAccount();
});
return (
<div>
<strong>AccountData</strong>
<AccountData
drizzle={drizzle}
drizzleState={drizzleState}
accountIndex={0}
units="ether"
precision={3}
/>
<table>
<tbody>
<tr>
<td>Drizzle</td>
<td>{drizzleAcc}</td>
<td>{drizzleBal}</td>
</tr>
<tr>
<td>Web3</td>
<td>{web3Acc}</td>
<td>{web3Bal}</td>
</tr>
</tbody>
</table>
</div>
);
};
export default AccountChangeDetection;