Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

formik does not work with initial value new Date

I am trying to have initial value of date like this, but when component renders it gives me error like

const formik = useFormik ({
    initialValues: {
    dob: new Date ()
    }
})

while doing so I am getting following error

Uncaught TypeError: date.isBefore is not a function

I am using formik with material UI Date Picker as below

 <LocalizationProvider dateAdapter={AdapterDayjs}>
      <DatePicker
           name="dob"
           id="dob"
           variant="standard"
           label="dob"
           value={formik.values.dob}
           renderInput={(params) => (
                <TextField {...params} />
           )}
           onChange={(value) => formik.setFieldValue('dob', value, true)}
                error={formik?.touched?.dob && formik?.errors?.dob ? true : false}
                helperText={formik.touched.dob && formik.errors.dob}
      />
 </LocalizationProvider>
                                
like image 654
Shraddha Alat Avatar asked Sep 28 '26 12:09

Shraddha Alat


1 Answers

If you are using the DatePicker from MUI (Material UI), the date has to be in dayjs.Dayjs type.

In initialValues, instead of dob: new Date (), do dob: dayjs(). That way you will have the current date and time in dob.

Later on, when you want to convert it to a javascript Date object, do dob.toDate().

like image 183
user2528260 Avatar answered Sep 30 '26 05:09

user2528260