I use the onGetAccount function to get the address of the logged user:
const [userWalletInfo, setUserWalletInfo] = useState()
async function onGetAccount() {
const account = await client.api.asset.getAccount();
return account;
}
useEffect(() => {
async function fetchUserWalletInfo() {
const address = await onGetAccount();
setUserWalletInfo({
address: address,
});
}
fetchUserWalletInfo();
}, []);
By doing so I am able to access userWalletInfo.address.
The problem is, if I load the component and after that (I mean that while the component run on localhost I edit code in VSCode, I did it to understand if address was set correctly) I edit the js. file adding:
<div> {userWalletInfo.address} </div>
It displays user address correctly, but if I refresh the page I get "TypeError: Cannot read property 'address' of undefined".
From this I infer that the page is rendered before fetchUserWalletInfo() runs out.
?for??is the optional chaining operator. It basically works like anifstatement. i.e. IfuserWalletInfoobject exists, then retrieve theaddressproperty. I've explained the same in my answer below.?is ES 2020 syntax, therefore you need to make sure you are using Bable in order to polyfill it. If you're using create react app, NextJS or something like that you most likely don't need to worry about this, but if you configured the React app from scratch you need to keep this in mind before shipping it?.operator is more commonly referred as "optional chaining operator". It’s just a syntax sugar that perform a nullish check to the left hand side operand before accessing its property, so you don’t get runtime error like the one you’ve got.