Skip to content

Commit

Permalink
fix multi-select that allows custom values bug
Browse files Browse the repository at this point in the history
  • Loading branch information
brahimmouhamou committed Apr 11, 2024
1 parent e2a45e5 commit e7c5a9b
Showing 1 changed file with 26 additions and 1 deletion.
27 changes: 26 additions & 1 deletion src/components/SearchSelect.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,31 @@ const SearchSelect = ({
session: { theme: vaultTheme },
} = useSession();

const findMatchingOption = (val: string) =>
options.find((option) => option.value === val);

const createNewOptionType = (val: string): OptionType => ({
label: val,
value: val,
});

const findOrCreateOption = (val: string): OptionType =>
findMatchingOption(val) ?? createNewOptionType(val);

// If the value is not in the options list, add it as a custom option
// It handles both single and multi-select cases
const addCustomOptionIfNeeded = (
updatedValues: OptionType | OptionType[] | undefined,
value: string | string[] | readonly string[] | undefined
): OptionType | OptionType[] | undefined => {
if (!value || !updatedValues || !Array.isArray(updatedValues))
return updatedValues;

return typeof value === 'string'
? findOrCreateOption(value)
: value.map(findOrCreateOption);
};

useEffect(() => {
if (!value) return;

Expand All @@ -71,7 +96,7 @@ const SearchSelect = ({

if (isCreatable) {
option = rest.isMulti
? ([{ label: value, value }] as OptionType[])
? addCustomOptionIfNeeded(option, value)
: ({ label: value, value } as OptionType);
}

Expand Down

0 comments on commit e7c5a9b

Please sign in to comment.