I am getting a strange behaviour from React useEffect and useState hooks: 7-8 times out of 10 it doesn't set vaults and it keeps having an empty object, while 2-3 times out of ten it does set it.
I am getting some data from the binance testnet blockchain correctly (console logs all log the right data each time, never get undefined) but when I am saving the data into vaults using useState, sometimes it saves it into vaults, sometimes it doesn't.
Somehow, sometimes (very few times) SetVault works and set vaults with the result from the blockchain, sometimes (most of the times) it just doesn't set anything.
Any idea on what is happening?
Code:
const [vaults, setVaults] = useState({});
useEffect(() => {
async function loadBloackchainData() {
const web3 = new Web3('https://data-seed-prebsc-1-s1.binance.org:8545/');
const vault = new web3.eth.Contract(VaultABI, testnet.Vaults[0].address);
const name = await vault.methods.symbol().call();
console.log('name: ', name); // ok data is logged correctly
const totalSupply = parseInt(await vault.methods.totalSupply().call());
console.log('totalSupply: ', totalSupply); // ok data is logged correctly
const totalBorrowed = parseInt(await vault.methods.vaultDebtVal().call());
console.log('totalBorrowed: ', totalBorrowed); // ok data is logged correctly
const capUtilRate = Number.isNaN(totalSupply / totalBorrowed) ? 0 : totalSupply / totalBorrowed;
console.log('capUtilRate: ', capUtilRate); // ok data is logged correctly
// ALL GOOD TILL HERE
setVaults(vaults => ({
...vaults,
[name]: {
totalSupply,
totalBorrowed,
capUtilRate,
},
}));
console.log('vaults inside useffect: ', vaults); // {}
}
loadBloackchainData();
}, []);
console.log('vaults outside useffect: ', vaults); // {}