0

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:

enter image description here

NOTE: In this example, I clicked the appointment__timeSlots button three times but the first click was console logged as undefined

d-dripz
  • 85
  • 1
  • 7
  • 1
    This happens due to async behavior and this question and answers should help you https://stackoverflow.com/q/54867616/7785337 .. Also moving the ```console.log(time)``` outside of the function will give you the result on button click.. Eg: https://codesandbox.io/s/react-functional-component-forked-q2gbq – Maniraj Murugan Oct 21 '20 at 03:06
  • @ManirajMurugan Very helpful! Thank you! – d-dripz Oct 21 '20 at 15:40

0 Answers0