Skip to content

Commit

Permalink
Fixed uncontrolled selection detection (#1935)
Browse files Browse the repository at this point in the history
  • Loading branch information
bmingles committed Apr 18, 2024
1 parent daa1730 commit f541b3e
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 3 deletions.
6 changes: 4 additions & 2 deletions packages/components/src/spectrum/picker/Picker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ export function Picker({
[tooltip]
);

// `null` is a valid value for `selectedKey` in controlled mode, so we check
// for explicit `undefined` to identify uncontrolled mode.
const isUncontrolled = selectedKey === undefined;
const [uncontrolledSelectedKey, setUncontrolledSelectedKey] =
useState(defaultSelectedKey);
Expand All @@ -93,10 +95,10 @@ export function Picker({
children: wrappedItems,
itemHeight: PICKER_ITEM_HEIGHTS.noDescription,
itemHeightWithDescription: PICKER_ITEM_HEIGHTS.withDescription,
selectedKey: selectedKey ?? uncontrolledSelectedKey,
selectedKey: isUncontrolled ? uncontrolledSelectedKey : selectedKey,
topOffset: PICKER_TOP_OFFSET,
}),
[selectedKey, uncontrolledSelectedKey, wrappedItems]
[isUncontrolled, selectedKey, uncontrolledSelectedKey, wrappedItems]
);

const onSelectionChangeInternal = useCallback(
Expand Down
4 changes: 3 additions & 1 deletion packages/jsapi-components/src/spectrum/Picker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ export function Picker({
}: PickerProps): JSX.Element {
const { getFormattedString: formatValue } = useFormatter(settings);

// `null` is a valid value for `selectedKey` in controlled mode, so we check
// for explicit `undefined` to identify uncontrolled mode.
const isUncontrolled = props.selectedKey === undefined;
const [uncontrolledSelectedKey, setUncontrolledSelectedKey] = useState(
props.defaultSelectedKey
Expand All @@ -63,7 +65,7 @@ export function Picker({
const getItemIndexByValue = useGetItemIndexByValue({
table,
columnName: keyColumn.name,
value: props.selectedKey ?? uncontrolledSelectedKey,
value: isUncontrolled ? uncontrolledSelectedKey : props.selectedKey,
});

const getInitialScrollPosition = useCallback(async () => {
Expand Down

0 comments on commit f541b3e

Please sign in to comment.