To render an HTML block after successfully setting a state variable, I have defined my state variables and functions below. The code snippet is as follows:
const formService = new FormService();
const [appointmentDate, setAppointmentDate] = useState<AppointmentDate>();
const [formattedDate, setFormattedDate] = useState<string>();
const [formattedTime, setFormattedTime ] = useState<string>();
const [formattedTime20MinutesBefore, setFormattedTime20MinutesBefore] = useState<string>();
useEffect(() => {
init();
},[])
const init = async () => {
await getAppointmentData();
await organizeTheDates();
}
const getAppointmentData = async () => {
const appointmentDateVar = await formService.getAppointmentPageInformation(3);
setAppointmentDate(appointmentDateVar);
}
const organizeTheDates = async () =>{
if (appointmentDate) {
// set the time and date variables
const date = new Date(appointmentDate.dateTime);
setFormattedDate(`${date.getDate().toString().padStart(2, '0')}/${(date.getMonth() + 1).toString().padStart(2, '0')}/${date.getFullYear()}`)
setFormattedTime(`${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`)
const twentyMinutesBefore = new Date(date.getTime() - 20 * 60000);
setFormattedTime20MinutesBefore(`${twentyMinutesBefore.getHours().toString().padStart(2, '0')}:${twentyMinutesBefore.getMinutes().toString().padStart(2, '0')}`);
}
}
Now, to render the code after the values are set, I have implemented an if-else block. However, when running the code, it gets stuck at the else page.
if(formattedDate !== undefined && formattedTime !== undefined ){
return ( ** my page ** ) }
}else {
return <div>loading</div>;
}
Upon saving the code in the IDE again, React re-renders the page and this time it enters the if block, indicating that the issue is due to the asynchronous nature of useState variables. Is there a way to resolve this? Thank you very much.
UPDATE
Following Quentin's answer, I made changes to the code as shown below. Thank you for your assistance.
const init = async () => {
await organizeTheDates(await getAppointmentData());
}
const getAppointmentData = async () => {
const appointmentDateVar = await formService.getAppointmentPageInformation(3);
setAppointmentDate(appointmentDateVar)
return appointmentDateVar;
}