diff --git a/components/TempDesignSystem/Form/Date/index.tsx b/components/TempDesignSystem/Form/Date/index.tsx index 7b9dbc083..4fe680bf6 100644 --- a/components/TempDesignSystem/Form/Date/index.tsx +++ b/components/TempDesignSystem/Form/Date/index.tsx @@ -1,5 +1,6 @@ "use client" import { parseDate } from "@internationalized/date" +import { useState } from "react" import { DateInput, DatePicker, Group } from "react-aria-components" import { useController, useFormContext, useWatch } from "react-hook-form" import { useIntl } from "react-intl" @@ -18,7 +19,7 @@ import type { Key } from "react-aria-components" import type { DateProps } from "./date" export default function DateSelect({ name, registerOptions = {} }: DateProps) { - const { formatMessage } = useIntl() + const intl = useIntl() const d = useWatch({ name }) const { control, setValue } = useFormContext() const { field } = useController({ @@ -26,6 +27,17 @@ export default function DateSelect({ name, registerOptions = {} }: DateProps) { name, rules: registerOptions, }) + + const [dateSegments, setDateSegment] = useState<{ + year: number | null + month: number | null + date: number | null + }>({ + year: null, + month: null, + date: null, + }) + const currentYear = new Date().getFullYear() const months = rangeArray(1, 12).map((month) => ({ value: month, @@ -41,17 +53,25 @@ export default function DateSelect({ name, registerOptions = {} }: DateProps) { * must subtract by 1 to get the selected month */ return (select: Key) => { - if (selector === DateName.month) { - select = Number(select) - 1 + const value = + selector === DateName.month ? Number(select) - 1 : Number(select) + const newSegments = { ...dateSegments, [selector]: value } + + if (Object.values(newSegments).every((val) => val !== null)) { + const newDate = dt(new Date()) + .set("year", newSegments.year!) + .set("month", newSegments.month!) + .set("day", newSegments.date!) + + setValue(name, newDate.format("YYYY-MM-DD")) } - const newDate = dt(d).set(selector, Number(select)) - setValue(name, newDate.format("YYYY-MM-DD")) + setDateSegment(newSegments) } } - const dayLabel = formatMessage({ id: "Day" }) - const monthLabel = formatMessage({ id: "Month" }) - const yearLabel = formatMessage({ id: "Year" }) + const dayLabel = intl.formatMessage({ id: "Day" }) + const monthLabel = intl.formatMessage({ id: "Month" }) + const yearLabel = intl.formatMessage({ id: "Year" }) let dateValue = null try { @@ -60,15 +80,14 @@ export default function DateSelect({ name, registerOptions = {} }: DateProps) { * date, but we can't check isNan since * we recieve the date as "1999-01-01" */ - dateValue = d ? parseDate(d) : null + dateValue = dt(d).isValid() ? parseDate(d) : null } catch (error) { console.error(error) } return (