DesktopDatePicker onChange getting the old value

Viewed 43

I am trying to get the date of the date in a custom function in the onChange function. The problem is that the function handleDatesChanged(), gets the previous date not the updated one.

 <DesktopDatePicker
              inputVariant="outlined"
              id="date-picker-dialog"
              label="Return date"
              disabled={queryParameterUsed ? true : false}
              fullWidth
              name="endDate"
              onChange={(val) => {
                formik.setFieldValue("endDate", val);
                handleDatesChanged(); //the function that I fetch data based on the date updated
              }}
              renderInput={(params) => <TextField {...params} />}
              onBlur={formik.handleBlur}
              value={formik.values.endDate}
              inputFormat="dd/MM/yyyy"
    
            />



 const handleDatesChanged = () => {
    console.log(formik.values.endDate); //Prints 24/08/2022 (previous date) When in fact it should supposed to print to 28/08/2022
}
1 Answers

The setFieldValue uses useReducer under the hood. It is async and new value is not available immediately. The same applies to the useState hook. You can pass new value as parameter of handler:

onChange={(val) => {
  formik.setFieldValue("endDate", val);
  handleDatesChanged(val);
}

const handleDatesChanged = (val) => {
    console.log(val);
}
Related