Hi all,
I am running into the following problem. I am looking to retrieve data from a web3 array and return that data in a React frontend. I have already worked out the code to function via an onclick event and this works just fine => the problem is I would like the data to be retrieved prior to page load or at the least as the page is loading without having the user to press a button.
As I am using the functional oriented coding as opposed to object oriented coding I have used useState and useEffect to mimic the component render part. Everything seems to work out on the mounting process and all works as it should however when I try to console log out the chainId and contractaddress (which I need to retrieve the data in the array) it seems that I cannot retrieve the data and it logs NaN/Null.
As stated if I press the button to execute the same code all works well however when I try to do the same thing prior to any rendering it returns NaN/null.
The reason that I am putting my question here is that I am starting to suspect that useMoralis() somehow doesnt work prior to rendering however this is purely a gut feeling. Does anyone have any experience with this and/or can help me.
Please find code below to get a sense of the problem:
export default function App() {
// Instantiate moralis and retrieve backend contract information.
const { Moralis, isWeb3Enabled, chainId: chainIdHex } = useMoralis();
const chainId = parseInt(chainIdHex);
const threadAddress =
chainId in contractAddresses ? contractAddresses[chainId][0] : null;
const [mounted, setMounted] = useState(false);
if (!mounted) {
console.log(âPrinted prior to renderâ);
console.log({ chainId });
console.log({ threadAddress });
}
useEffect(() => {
setMounted(true);
console.log(âmountedâ);
}, []);
}