Issue
Compiles ok but Getting undefined in state. Appreciate any advice!
customer_data = customer_data?.listCustomers[0];
console.log(customer_data?.sunday_open); /// returns 08:00:00
const [accountInfo, setAccountInfo] = useState({ "sunday_open_hours": customer_data?.sunday_open.split(":")[0],
"sunday_open_mins" : customer_data?.sunday_open.split(":")[1]});
console.log(accountInfo)
this code:
console.log(accountInfo)
returns:
{sunday_open_hours: undefined, sunday_open_mins: undefined}
Solution
Maybe because it takes time to load the data so in this case you need to wait/watch for a change of the retrieved data and update the state according to it. Like this in short
export default function App() {
const [accountInfo, setAccountInfo] = useState({})
useEffect(() => {
if (customer_data)
setAccountInfo({ "sunday_open_hours": customer_data?.sunday_open.split(":")[0],
"sunday_open_mins" : customer_data?.sunday_open.split(":")[1]});
},[customer_data])
console.log(accountInfo)
}
Answered By - DINO
Answer Checked By - - Timothy Miller (ReactFix Admin)