Trying to use recently set state immediately may result in nulls

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the react category.

Last Updated: 2021-05-16

I had the following code:

const { appointmentSlots, setAppointmentSlots } = useState([])

function handleLocationStep() {
  Api.slots(
    {
      testType: "covid19-test",
      country: "germany",
      postcode: formData.location,
    },
    globalState.apiToke
  )
    .then((response) => {
      // Setting state with a hook
      setAppointmentSlots(response.data);
      // Guess what is logged at this point?
      log(appointmentSlots)

      handleStepChange("Station", 0.35);
    })
    .catch(reportError);
}

No matter what, null was being logged, even though every external sign suggested it should have data.

The fix was just to remove the logging of the react state getter and log the actual data instead. This was because state changes in React are async and won't show up immediately.

log(response.data)
// vs log(appointmentSlots)

Lesson:

State changes in React are async (e.g. setCounter) and will only show up during next render. Attempting to use those variable straight away will lead to issues.