0

I am working on one reactjs project. where the user needs to pick two different dates starting date and end date. When a user picks first date i need to update the state to check whether the starting date should be less than closing date ,But the problem i am facing is setState not updating state immediately. I am facing this problem during update the store timings .How can i fix this problem.

const [storeTimings, setStoreTimings] = useState({
    startTime: "",
    endTime: "",
    startTime2: "",
    endTime2: "",
  });



const isValidTime = (key, value) => {
    setStoreTimings({ ...storeTimings, [key]: value });
    console.log({ key, value });
  };
<DatePicker
onChange={(date) => {
isValidTime("startTime", date);
            }}
          />
Andaman
  • 295
  • 3
  • 10
  • 2
    *"setState not updating state immediately"* - That's correct. State updates are asynchronous and batched for performance. Where specifically are you observing this problem and what exactly is the problem? – David May 06 '22 at 18:15
  • 1
    State setters can also take a function to update the state. This callback is given the previous state which is what you want. – kelsny May 06 '22 at 18:17

1 Answers1

0

State setters can also take a function to update the state. This callback is given the previous state which is what you want.

You should use an updater function instead because using storeTimings directly is not guaranteed to reference the state of your component when you want to update it. Using this function to get the previous state directly before the update allows you to always use the latest state:

  const [storeTimings, setStoreTimings] = useState({
    startTime: "",
    endTime: "",
    startTime2: "",
    endTime2: "",
  });

  const isValidTime = (key, value) => {
    // provide updater function
    setStoreTimings((previous) => ({ ...previous, [key]: value }));
    console.log({ key, value });
  };

  <DatePicker
    onChange={(date) => {
      isValidTime("startTime", date);
    }}
  />

More details about this function argument to state setters can be found in this question.

kelsny
  • 23,009
  • 3
  • 19
  • 48