Skip to content

Commit

Permalink
[Select]: fix onValueChange will call with empty string when side form
Browse files Browse the repository at this point in the history
  • Loading branch information
himself65 committed Nov 27, 2024
1 parent 4584a37 commit bad36eb
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 1 deletion.
57 changes: 57 additions & 0 deletions packages/react/select/src/Select.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { css } from '../../../../stitches.config';
import * as Select from '@radix-ui/react-select';
import { Label } from '@radix-ui/react-label';
Expand Down Expand Up @@ -511,6 +512,62 @@ export const WithinForm = () => {
);
};

export const RefreshItemsWithinForm = function SelectDemo() {
const [value, setValue] = React.useState<string>('apple');
const [hide, setHide] = React.useState(false);

return (
<form onSubmit={(e) => e.preventDefault()}>
<p>current value: {value}</p>
<button
onClick={() => {
ReactDOM.flushSync(() => {
setHide(true);
});
ReactDOM.flushSync(() => {
setValue('banana');
setHide(false);
});
}}
>
Update to banana
</button>

<Select.Root value={value} onValueChange={setValue}>
<Select.Trigger className={triggerClass()}>
<Select.Value placeholder="select a fruit" />
<Select.Icon />
</Select.Trigger>
<Select.Portal>
<Select.Content className={contentClass()}>
<Select.Viewport className={viewportClass()}>
{hide ? null : (
<>
<Select.Item className={itemClass()} value="apple">
<Select.ItemText>Apple</Select.ItemText>
</Select.Item>
<Select.Item className={itemClass()} value="banana">
<Select.ItemText>Banana</Select.ItemText>
</Select.Item>
<Select.Item className={itemClass()} value="blueberry">
<Select.ItemText>Blueberry</Select.ItemText>
</Select.Item>
<Select.Item className={itemClass()} value="grapes">
<Select.ItemText>Grapes</Select.ItemText>
</Select.Item>
<Select.Item className={itemClass()} value="pineapple">
<Select.ItemText>Pineapple</Select.ItemText>
</Select.Item>
</>
)}
</Select.Viewport>
</Select.Content>
</Select.Portal>
</Select.Root>
</form>
);
};

export const DisabledWithinForm = () => {
const [data, setData] = React.useState({});

Expand Down
3 changes: 2 additions & 1 deletion packages/react/select/src/Select.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1615,7 +1615,8 @@ const BubbleSelect = React.forwardRef<HTMLSelectElement, React.ComponentPropsWit
if (prevValue !== value && setValue) {
const event = new Event('change', { bubbles: true });
setValue.call(select, value);
select.dispatchEvent(event);
// delay the dispatch to the next tick to ensure React has updated the select options
window.setTimeout(() => select.dispatchEvent(event));
}
}, [prevValue, value]);

Expand Down

0 comments on commit bad36eb

Please sign in to comment.