Skip to content

Commit f39ad54

Browse files
committed
fix(core): not propagate undefined time value from the timeInput
1 parent 17cf89a commit f39ad54

File tree

1 file changed

+21
-3
lines changed
  • packages/sanity/src/core/components/inputs/DateInputs/calendar

1 file changed

+21
-3
lines changed

packages/sanity/src/core/components/inputs/DateInputs/calendar/Calendar.tsx

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -179,10 +179,28 @@ export const Calendar = forwardRef(function Calendar(
179179
[onSelect, savedSelectedDate, timeZone],
180180
)
181181

182+
const timeFromDate = useMemo(() => format(savedSelectedDate, 'HH:mm'), [savedSelectedDate])
183+
const [timeValue, setTimeValue] = useState<string | undefined>(timeFromDate)
184+
185+
useEffect(() => {
186+
// The change is coming from another source, so we need to update the timeValue to the new value.
187+
// eslint-disable-next-line react-hooks/no-deriving-state-in-effects
188+
setTimeValue(timeFromDate)
189+
}, [timeFromDate])
190+
182191
const handleTimeChangeInputChange = useCallback(
183192
(event: FormEvent<HTMLInputElement>) => {
184-
const date = parse(event.currentTarget.value, 'HH:mm', new Date())
185-
handleTimeChange(date.getHours(), date.getMinutes())
193+
const value = event.currentTarget.value
194+
if (value) {
195+
const date = parse(value, 'HH:mm', new Date())
196+
handleTimeChange(date.getHours(), date.getMinutes())
197+
setTimeValue(value)
198+
} else {
199+
// Setting the timeValue to undefined will let the input behave correctly as a time input while the user types.
200+
// This means, that until it has a valid value the time input input won't emit a new onChange event.
201+
// but we cannot send the undefined value to the handleTimeChange, because it expects a valid date.
202+
setTimeValue(undefined)
203+
}
186204
},
187205
[handleTimeChange],
188206
)
@@ -377,7 +395,7 @@ export const Calendar = forwardRef(function Calendar(
377395
<Flex align="center">
378396
<TimeInput
379397
aria-label={labels.selectTime}
380-
value={format(savedSelectedDate, 'HH:mm')}
398+
value={timeValue}
381399
onChange={handleTimeChangeInputChange}
382400
/**
383401
* Values received in timeStep are defined in minutes as shown in the docs https://www.sanity.io/docs/studio/datetime-type#timestep-47de7f21-25bc-468d-b925-cd30e2690a7b

0 commit comments

Comments
 (0)