-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Description
Provide a general summary of the feature here
We're implementing a custom DateRangePicker
with all related hooks incl. useDateRangePickerState
.
It seems to be hard to clear the state in a good way.
What we have done for our DatePicker
is already a little hacky, as we repeatedly call fieldState.clearSegment
for each segment.
It's not possible to do it like this when having to call clearSegment
for both startFieldState
and endFieldState
though, as the value
, used when clearSegment
via setDateTime
sets the useDateRangePickerState
value
, is stale.
Meaning that when running endFieldState.clearSegment
it will set the { start: ... }
part back to the last selected value, because endFieldState.clearSegment
is not aware that it has just been reset by startFieldState.clearSegment
.
We could of course just do dateRangePickerState.setValue({ start: null!, end: null! })
(though null is not accepted by TS).
But clearSegment
is doing other useful stuff like saving last selected value
to be used for a re-selection.
What we've found would work is if the value
was saved as a ref
(which you've done before) for the latest state to be used in endFieldState.clearSegment
call:
// useDateRangePickerState.ts
let value = controlledValue || placeholderValue;
let valueRef = useRef(value);
valueRef.current = value;
let setValue = (value: DateRange) => {
valueRef.current = value;
...
}
setDateTime(part, dateTime) {
setValue({ ...valueRef.current, [part]: dateTime });
},
But even better if a new method like clearAllSegments
would be made available to avoid the repeated calls as well.
Are we overlooking something? Is there another way to achieve this clearing properly?
🤔 Expected Behavior?
Calling startFieldState.clearSegment
then endFieldState.clearSegment
should fully clear value of useDateRangePickerState
.
😯 Current Behavior
Calling startFieldState.clearSegment
then endFieldState.clearSegment
sets start-part of value
of useDateRangePickerState
back to last selected value.
💁 Possible Solution
// useDateRangePickerState.ts
let value = controlledValue || placeholderValue;
let valueRef = useRef(value);
valueRef.current = value;
let setValue = (value: DateRange) => {
valueRef.current = value;
...
}
setDateTime(part, dateTime) {
setValue({ ...valueRef.current, [part]: dateTime });
},
Even better if a new method like clearAllSegments
would be made available to avoid the repeated calls as well.
🔦 Context
This is how we work around it to both make clearSegment do the extra stuff it does (even though only taking effect for the end field) and also end up with a fully cleared state value:
const clearFields = () => {
segmentTypes.forEach((segmentType) => {
startFieldState.clearSegment(segmentType)
endFieldState.clearSegment(segmentType)
});
dateRangePickerState.setValue({ start: null!, end: null! });
};
💻 Examples
No response
🧢 Your Company/Team
No response
🕷 Tracking Issue
No response