Goal: Set the date
and time
states variables.
Problem: When I click on the appointment__timeSlots
button the first time, the console prints undefined
and I am unable to set the state of the time
variable.
However, when I click on the button a second time, the console prints the time as expected.
I'm using functional components:
function Appointment() {
const [date, setDate] = useState(new Date());
const [time, setTime] = useState();
const handleDate = (date) => {
console.log(date);
setDate(date);
};
const handleTime = (e) => {
e.preventDefault();
const selectedTime = e.target.value;
setTime(selectedTime);
console.log(time);
};
// post date & time to db
const postAppointment = (e) => {
e.preventDefault();
db.collection("appointments").add({
date: date,
time: time,
});
};
And here is the code that renders on the page:
return (
<div className="request__work">
<div className="calendar">
<form>
<Calendar
className="react-calendar"
onChange={handleDate}
value={date}
/>
<div className="appointment__timeSlots">
<button
className="appointment__button"
value="9:00am"
onClick={handleTime}
>
9:00am
</button>
</div>
<button type="submit" onClick={postAppointment}>
Request
</button>
</form>
</div>
</div>
);
}
Here is a screen shot of what happens when I click on the appointment__timeSlots
button:
NOTE: In this example, I clicked the appointment__timeSlots
button three times but the first click was console logged as undefined