0

I initialise missingWeekDays as an empty array []. I create an array of strings weekdays and assign to missingWeekDays. But when I console out weekdays has content but missingWeekDays is still empty. Why is that?

Some suggested that setMissingWeekDays should have a callback like old setState. But I can't find any documentation on this callback... A link would be appreciated!

import React, { FC, useEffect, useState } from 'react'

const Component: FC = () => {

    const initialStart = moment()
        .year(2018)
        .week(5)
        .startOf('isoWeek')

    const [missingWeekDays, setMissingWeekDays] = useState<string[]>([])
    const [startDate, setStartDate] = useState(initialStart)

    useEffect(() => {
        const weekdays = createWeekdaysList(startDate.toDate())
        setMissingWeekDays(weekdays)
        console.log(missingWeekDays, weekdays)
    }, [startDate])

    return <CigarettesDetails onTimeChange={handleTimeChange} data={data} />
}

export default CigarettesDetailsContainer

const createWeekdaysList = (startDate: Date): string[] => {
    const weekdaysList: string[] = []

    let weekDay = 0
    while (weekDay < 7) {
        const date: string = moment(startDate)
            .clone()
            .add(weekDay, 'day')
            .format('YYYY-MM-DD')

        weekdaysList.push(date)
        weekDay += 1
    }

    return weekdaysList
}
olefrank
  • 6,452
  • 14
  • 65
  • 90
  • Has a dup. `console.log` should be passed as a second argument inside `setMissingWeekdays` – Joseph D. Oct 03 '19 at 09:09
  • Possible duplicate of [When to use React setState callback](https://stackoverflow.com/questions/42038590/when-to-use-react-setstate-callback) – Joseph D. Oct 03 '19 at 09:10

1 Answers1

0

Your setter from useState gets handled asynchronously. This results in your console log not having the updated data. This thread adds more color for you:

useState set method not reflecting change immediately

Craig Gehring
  • 3,067
  • 1
  • 9
  • 11