From 593177f6e16138ce61547131cac832eb72f4fdb5 Mon Sep 17 00:00:00 2001 From: Flavio Mastrangelo Date: Tue, 25 Feb 2025 20:40:39 +0100 Subject: [PATCH] fix: TagInput component values initialization --- .../Objects/StyledElements/Form/TagInput.tsx | 31 ++++++++++++++----- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/apps/web/components/Objects/StyledElements/Form/TagInput.tsx b/apps/web/components/Objects/StyledElements/Form/TagInput.tsx index ffd78059..6a720ded 100644 --- a/apps/web/components/Objects/StyledElements/Form/TagInput.tsx +++ b/apps/web/components/Objects/StyledElements/Form/TagInput.tsx @@ -1,4 +1,4 @@ -import React, { useState, Dispatch, SetStateAction } from 'react' +import React, { useState, Dispatch, SetStateAction, useEffect } from 'react' import { Tag, TagInput } from 'emblor' interface FormTagInputProps { @@ -16,14 +16,29 @@ const FormTagInput = ({ error, placeholder, }: FormTagInputProps) => { - const initialTags = value - ? value.split(separator).map((text, i) => ({ - id: i.toString(), - text: text.trim(), - })) - : [] + const [tags, setTags] = useState(() => + value && typeof value === 'string' + ? value.split(separator).filter(text => text.trim()).map((text, i) => ({ + id: i.toString(), + text: text.trim(), + })) + : [] + ); + + useEffect(() => { + if (value && typeof value === 'string') { + const newTags = value.split(separator) + .filter(text => text.trim()) + .map((text, i) => ({ + id: i.toString(), + text: text.trim(), + })); + setTags(newTags); + } else { + setTags([]); + } + }, [value, separator]); - const [tags, setTags] = useState(initialTags) const [activeTagIndex, setActiveTagIndex] = useState(null) const handleTagsChange: Dispatch> = (