Grafana-UI: Fix setting default value for MultiSelect (#30671) (#30687)

* Grafana-ui: Default value to undefned vs empty array

* Grafana-ui: Remove log

* Grafana-ui: Update tests

(cherry picked from commit aad7d495ec)

Co-authored-by: Alex Khomenko <Clarity-89@users.noreply.github.com>
This commit is contained in:
Grot (@grafanabot)
2021-01-28 09:39:00 +02:00
committed by GitHub
co-authored by Alex Khomenko
parent 89d5428954
commit b3425159e1
3 changed files with 11 additions and 13 deletions
@@ -150,7 +150,7 @@ export function SelectBase<T>({
let ReactSelectComponent: ReactSelect | Creatable = ReactSelect;
const creatableProps: any = {};
let asyncSelectProps: any = {};
let selectedValue = [];
let selectedValue;
if (isMulti && loadOptions) {
selectedValue = value as any;
} else {
@@ -207,7 +207,7 @@ export function SelectBase<T>({
renderControl,
showAllSelectedWhenOpen,
tabSelectsValue,
value: isMulti ? selectedValue : selectedValue[0],
value: isMulti ? selectedValue : selectedValue?.[0],
};
if (allowCustomValue) {
@@ -74,11 +74,11 @@ describe('Select utils', () => {
expect(cleanValue('test1', optGroup)).toEqual([{ label: 'Group 4 - Option 1', value: 'test1' }]);
expect(cleanValue(3, options)).toEqual([{ label: 'Option 3', value: 3 }]);
});
it('should return empty array for null/undefined/empty values', () => {
expect(cleanValue([undefined], options)).toEqual([]);
expect(cleanValue(undefined, options)).toEqual([]);
expect(cleanValue(null, options)).toEqual([]);
expect(cleanValue('', options)).toEqual([]);
it('should return undefined for null/undefined/empty values', () => {
expect(cleanValue([undefined], options)).toEqual(undefined);
expect(cleanValue(undefined, options)).toEqual(undefined);
expect(cleanValue(null, options)).toEqual(undefined);
expect(cleanValue('', options)).toEqual(undefined);
});
});
});
@@ -4,12 +4,10 @@ import { SelectableOptGroup } from './types';
/**
* Normalize the value format to SelectableValue[] | []. Only used for single select
*/
export const cleanValue = (
value: any,
options: Array<SelectableValue | SelectableOptGroup | SelectableOptGroup[]>
): SelectableValue[] | [] => {
export const cleanValue = (value: any, options: Array<SelectableValue | SelectableOptGroup | SelectableOptGroup[]>) => {
if (Array.isArray(value)) {
return value.filter(Boolean);
const filtered = value.filter(Boolean);
return filtered?.length ? filtered : undefined;
}
if (typeof value === 'object' && value !== null) {
return [value];
@@ -20,7 +18,7 @@ export const cleanValue = (
return [selectedValue];
}
}
return [];
return undefined;
};
/**