In my project I am having trouble setting a state variable with a javascript object, I can see in my console logs that the object is being instansiated correctly with the right values, but I cannot figure out why it is not properly setting the state hook.
Any help would be appreciate!!
const [accountInfo, setAccountInfo] = useState({})
const delay = ms => new Promise(res => setTimeout(res, ms));
const onLogin = async (account) => {
await(delay(2000));
console.log(account); // I am getting the proper output of the object here
if(account.account_id != -1){
setAccountInfo(account);
await delay(4000); //Just for debugging
console.log("acc " + accountInfo); // This outputs [Object object]
setLoggedIn(true);
}else{
alert('Account does not exist');
}
}
You are trying to concatenate string with object. Either convert object to string with JSON.stringify or use object.property.
console.log("Object" + JSON.stringify(object_to_print));
you are trying to console.log a state variable. React is not guaranteeing the state change immediately. you can access state change in useEffect hook
useEffect(() => {
console.log('state changed', your-state-variable)
// write your callback function here
}, [your-state-variable]);