0

This is how I declare my state :

const [pickedDates, setPickedDates] = useState(['','']);

This is the callback for the RangePicker's onChange:

  const handleDateChange = (dates:any,dateString:any) => {
    if(dates){
      let startDate = dateString[0];
      let endDate = dateString[1];
      console.log(startDate);
      console.log(endDate);
      setPickedDates([startDate,endDate]);
      console.log(pickedDates);
    }
  }

And this is how I have my RangePicker:

<RangePicker onChange={handleDateChange}/>

The issue is that when I pick the start and end date from the RangePicker, the pickedDates state should update and should have the start and end date. But it doesn't, not until the next time I change the dates on the RangePicker, then it has the previous dates instead. Essentially, it is always one step behind. I know this because I printed the pickedDates state in the handleDateChange callback.

Here is an output from the console:

enter image description here

As you can see, the first time when I selected two dates, the pickedDates state is actually empty ['','']. Then I select a new set of dates and now the pickeDates state has the previous dates that I selected. I am not sure what is going on. I'd really appreciate some help!

This is what the RangePicker looks like:

enter image description here

  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Konrad Mar 12 '23 at 09:33

1 Answers1

0

It is not showing the latest value in the console.log() because of the asynchronous nature of setState, Thus you are getting the previous value.

If you want to perform an action on state update, you need to use the useEffect hook

Check the following code

App.jsx

import React, { useState, useEffect } from "react";
import "./index.css";
import { DatePicker, Space } from "antd";
const { RangePicker } = DatePicker;
const App = () => {
  const [pickedDates, setPickedDates] = useState(["", ""]);

/* if you want to perform an action on state update, you need to use the useEffect hook */

  useEffect(() => {
    // action on update of pickedDates
    console.log("Output from useEffect:",pickedDates); /* here pickedDates will have the latest value*/
  }, [pickedDates]);

  const handleDateChange = (dates, dateString) => {
    if (dates) {
      let startDate = dateString[0];
      let endDate = dateString[1];
      console.log(startDate);
      console.log(endDate);
      setPickedDates([startDate, endDate]);
      console.log("Output from handleDateChange:",pickedDates); /* here pickedDates does not have the latest value */
    }
  };

  return (
    <Space direction="vertical" size={12}>
      <RangePicker onChange={handleDateChange} />
    </Space>
  );
};
export default App;

Output:

output

Ved
  • 938
  • 2
  • 5
  • 19