408 words
2 minutes
Abnormal Selection Behavior in Fusion's DatePicker2 Component

This afternoon a colleague ran into yet another odd bug, this time in the DatePicker2 component of the Fusion component library. Here’s the scenario: two date pickers, a start date and an end date. Click the end-date picker first and pick any date — the selection fails with the message “Please select the start date first”, and the end date doesn’t change, because the onChange handler checks whether the start date is set and bails out if it isn’t. But now select the start date, then go back to the end-date picker — and here’s the kicker — you don’t even need to pick a date this time. Just open the popup and close it, and the end date gets set. To the exact date that failed the first time around.

Reproducing the Issue#

Open the Fusion website, find the DatePicker2 component, and modify the code in the size example as follows:

function Demo() {
const [first, setFirst] = React.useState('');
const [second, setSecond] = React.useState('');
return (
<div>
<DatePicker2 value={first} onChange={(_, str) => {
setFirst(str);
}} />
<DatePicker2 value={second} onChange={(_, str) => {
if (!first) {
return;
}
setSecond(str);
}} />
</div>
);
}
ReactDOM.render(<Demo />, mountNode);

Pick the second date picker first and choose a date — the selection fails. Then pick a date with the first picker, open the second picker again, and this time just open the popup and close it without choosing anything. The selection now goes through.

That’s all it takes to reproduce the bug.

Analyzing the Issue#

The behavior is bizarre: the first date selection fails, but the second one succeeds — and with the very date that failed the first time. It smells like a state-update problem, so my theory was that DatePicker2 internally stores the failed selection on the first attempt, and on the second attempt — even though no date was actually picked — it quietly reuses that stored value. The component’s documentation doesn’t offer any way to reset its internal state, so I forced a remount with the key prop, which makes the problem disappear.

The Fix#

function Demo() {
const [first, setFirst] = React.useState('');
const [second, setSecond] = React.useState('');
return (
<div>
<DatePicker2 value={first} onChange={(_, str) => {
setFirst(str);
}} />
{/* use key to force a remount of the component */}
<DatePicker2 key={Date.now()} value={second} onChange={(_, str) => {
if (!first) {
return;
}
setSecond(str);
}} />
</div>
);
}
ReactDOM.render(<Demo />, mountNode);
Abnormal Selection Behavior in Fusion's DatePicker2 Component
https://www.mihouo.com/en/posts/front/abnormal-behavior-in-fusions-datepicker2-component/
Author
Jia
Published at
2024-09-05
License
CC BY-NC-SA 4.0