Playing with Flowbite React and their Datepicker component, I had data coming from the backend in this or similar form:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
{ "data": { "posts": { "edges": [ { "node": { "id": "c57e4ea8-072e-4057-974f-bfb369504a57", "createdAt": "2024-10-24T12:21:20Z", "updatedAt": "2024-10-24T14:03:16Z", "title": "Jobangebot mit jemand ohne Namen", "body": "Dies ist ein Jobangebot von jemandem ohne Namen", "expires": true, "expireTime": "2024-10-31T23:00:00Z", "category": { "id": "df84950d-742b-4d07-9f11-04b8964bcb36", "title": "Jobangebote" }, "profile": { "id": "0ce6ee59-4ebf-42cf-9c3a-69cf5e826b0b", "sub": "288686157058342913", "name": "" } } } ] } } } |
aka
1 |
"expireTime": "2024-10-31T23:00:00Z", |
React is a bit of a cringy special child. Angular, no problemo. Vue, no problemo.
Anyhow.
I have to set defaultValues in a React-hook-form form, because React is special with controlled and uncontrolled components.
aka
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
type AdminPostEditFormValues = { title: string, body: string, expires: boolean, expireTime: Date, } const {control, handleSubmit, watch, formState: {errors}} = useForm<AdminPostEditFormValues>({ defaultValues: { title: data?.posts?.edges[0]?.node?.title, body: data?.posts?.edges[0]?.node?.body, expires: data?.posts?.edges[0]?.node?.expires, expireTime: dayjs(data?.posts?.edges[0]?.node?.expireTime).toDate() || dayjs().toDate(), } }) |
So, I’m using dayjs for my date/time stuff, and this line essentially means, parse the Date before assigning it to a form value (or create a new Date(), because React and controlled/uncontrolled forms is not a happy story).
1 |
expireTime: dayjs(data?.posts?.edges[0]?.node?.expireTime).toDate() || dayjs().toDate(), |
TL;DR: Parse the date value coming from the backend into a Date object. e.g.
1 |
Date.parse("2024-10-31T23:00:00Z") |