From fc12b9c8456046697b7b252e84fa5f20c31089b5 Mon Sep 17 00:00:00 2001 From: Donkoko Date: Thu, 25 Jul 2024 15:29:16 +0300 Subject: [PATCH] dont allow duplicate options on custom fields: - make sure when importing the array of options is unique - handle error in UI when trying to add 2 options with the same name --- app/components/forms/option-builder.tsx | 12 +++++++++--- app/modules/custom-field/service.server.ts | 4 ++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/app/components/forms/option-builder.tsx b/app/components/forms/option-builder.tsx index 15db9d4f1..951f9cd32 100644 --- a/app/components/forms/option-builder.tsx +++ b/app/components/forms/option-builder.tsx @@ -12,6 +12,7 @@ interface Props { function OptionBuilder({ options, onAdd, onRemove, disabled }: Props) { const [opt, setOpt] = useState(""); + const [error, setError] = useState(""); return (
@@ -19,17 +20,22 @@ function OptionBuilder({ options, onAdd, onRemove, disabled }: Props) { onChange={({ target }) => setOpt(target.value)} label="" value={opt} - defaultValue={opt} placeholder="Type an option here and press enter" disabled={disabled} className="w-full" + error={error} hideLabel onKeyDown={(e) => { if (e.key == "Enter") { e.preventDefault(); if (opt) { - onAdd(opt); - setOpt(""); + if (options.includes(opt)) { + setError("Option already exists"); + } else { + onAdd(opt); + setOpt(""); + setError(""); + } } } }} diff --git a/app/modules/custom-field/service.server.ts b/app/modules/custom-field/service.server.ts index 894838efd..e77b9d095 100644 --- a/app/modules/custom-field/service.server.ts +++ b/app/modules/custom-field/service.server.ts @@ -268,10 +268,10 @@ export async function createCustomFieldsIfNotExists({ for (const [customFieldDefStr, def] of Object.entries(fieldToDefDraftMap)) { if (def.type === "OPTION" && optionMap[customFieldDefStr]?.length) { - def.options = optionMap[customFieldDefStr]; + const uniqueSet = new Set(optionMap[customFieldDefStr]); + def.options = Array.from(uniqueSet); } } - return await upsertCustomField(Object.values(fieldToDefDraftMap)); } catch (cause) { throw new ShelfError({