Skip to content

Commit

Permalink
🐛 Autocomplete: controlled singleselect bug (#3614)
Browse files Browse the repository at this point in the history
controlled single select: Update internal selecteditem state when this is changed from the outside
  • Loading branch information
oddvernes authored Sep 5, 2024
1 parent 47f82e5 commit ed2d982
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,41 @@ Multiple.args = {
options: stocks,
}

export const ControlledSingleSelect: StoryFn<
AutocompleteProps<MyOptionType>
> = () => {
const [selectedOptions, setSelectedOptions] = useState([])
const options = ['option 1', 'option 2', 'option 3', 'option 4']
const isOptionDisabled = (item: string) => item === 'option 3'
return (
<div>
<Autocomplete
label="test"
options={options}
selectedOptions={selectedOptions}
onOptionsChange={({ selectedItems: options }) =>
setSelectedOptions(options)
}
optionDisabled={isOptionDisabled}
/>
<Button
onClick={() => {
setSelectedOptions([
options.filter((option) => !selectedOptions.includes(option))[
Math.floor(Math.random() * (options.length - 1))
],
])
}}
>
Change to random other option
</Button>
<Typography>Selected option is: {selectedOptions[0]}</Typography>
</div>
)
}
//this story is for internal testing, so by default we hide the story from the sidebar
ControlledSingleSelect.tags = ['!dev']

export const OptionLabel: StoryFn<AutocompleteProps<MyOptionType>> = (args) => {
const { options } = args

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -684,6 +684,11 @@ function AutocompleteInner<T>(
allDisabled,
}),
}
case useCombobox.stateChangeTypes.ControlledPropUpdatedSelectedItem:
setSelectedItems([changes.selectedItem])
return {
...changes,
}
default:
return changes
}
Expand Down

0 comments on commit ed2d982

Please sign in to comment.