Hunor
Hunor

Reputation: 449

Date setting not working in react "useState"

I am trying to use the useState hook in react and as a default value I want to set an incoming props value (startDate). Unfortunately, it is always setting in the actual/current date. What am I getting wrong here?

My code:

 export type CalendarProps = {
  startDate: Date,
  endDate: Date,
};

const SomeCalendarView: React.FC = (props: CalendarProps) => {
  console.log(props.startDate);
  const [selectedDay, setSelectedDay] = useState(props.startDate);
  console.log(selectedDay);
  ....

My console log: Console Log

May 12 - is my incoming startDate.

May 14 - is my current date/time.

Why I am getting the actual time? Any ideas?

Upvotes: 1

Views: 7931

Answers (1)

Hunor
Hunor

Reputation: 449

I wasn't aware, that my props dates (startDate and endDate) are coming with a delay and the useState default is getting value instantly (and because the props date was not available, it was populated with the actual/current date). I had to use useEffect to set my state as soon as the props are changing. Like here:

const [selectedDay, setSelectedDay] = useState();
const [selectedStage, setSelectedStage] = useState();

useEffect(
  () => {
    setSelectedDay(props.startDate);
    setSelectedStage(props.stages.valueSeq().first());
  },
  [props.startDate, props.stages],
);

Upvotes: 1

Related Questions