Files
grafana/public/app/plugins/datasource/elasticsearch/components/hooks/useCreatableSelectPersistedBehaviour.ts
renovate[bot] d87cd6f26c Update dependency prettier to v2.5.1 (#43473)
* Update dependency prettier to v2.5.1

* prettier fixes

* chore(toolkit): bump prettier to 2.5.1

* style(eslint): bump grafana config to 2.5.2 in core and toolkit

* style(mssql-datasource): fix no-inferrable-types eslint errors

Co-authored-by: Renovate Bot <bot@renovateapp.com>
Co-authored-by: Ashley Harrison <ashley.harrison@grafana.com>
Co-authored-by: Jack Westbrook <jack.westbrook@gmail.com>
2022-02-02 12:02:32 +00:00

49 lines
1.3 KiB
TypeScript

import { SelectableValue } from '@grafana/data';
import { useState } from 'react';
const hasValue =
<T extends SelectableValue>(searchValue: T['value']) =>
({ value }: T) =>
value === searchValue;
const getInitialState = (initialOptions: SelectableValue[], initialValue?: string): SelectableValue[] => {
if (initialValue === undefined || initialOptions.some(hasValue(initialValue))) {
return initialOptions;
}
return [
...initialOptions,
{
value: initialValue,
label: initialValue,
},
];
};
interface Params {
options: SelectableValue[];
value?: string;
onChange: (s: SelectableValue<string>) => void;
}
/**
* Creates the Props needed by Select to handle custom values and handles custom value creation
* and the initial value when it is not present in the option array.
*/
export const useCreatableSelectPersistedBehaviour = ({ options: initialOptions, value, onChange }: Params) => {
const [options, setOptions] = useState(getInitialState(initialOptions, value));
const addOption = (newValue: string) => setOptions([...options, { value: newValue, label: newValue }]);
return {
onCreateOption: (value: string) => {
addOption(value);
onChange({ value });
},
onChange,
allowCustomValue: true,
options,
value,
};
};