From 4e74747277c99ead7596111b0f14fa7a9cd006f2 Mon Sep 17 00:00:00 2001 From: Harish Mohan Raj Date: Mon, 19 Aug 2024 13:29:42 +0530 Subject: [PATCH] Change selectbox into a controlled component --- .../components/buildPage/ModelSelector.tsx | 33 +++++++++++++++---- 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/app/src/client/components/buildPage/ModelSelector.tsx b/app/src/client/components/buildPage/ModelSelector.tsx index 3d7f65b5..e3f8a536 100644 --- a/app/src/client/components/buildPage/ModelSelector.tsx +++ b/app/src/client/components/buildPage/ModelSelector.tsx @@ -1,3 +1,4 @@ +import { useEffect, useMemo, useState } from 'react'; import Select, { StylesConfig, SingleValue } from 'react-select'; import { PropertySchemaParser, SetUpdateFormStack } from './PropertySchemaParser'; import { SelectOption } from './PropertySchemaParser'; @@ -10,8 +11,28 @@ export const ModelSelector = ({ parser: PropertySchemaParser | null; updateFormStack: SetUpdateFormStack; }) => { - const selectOptions = parser?.getModelNames(); + const selectOptions = useMemo(() => parser?.getModelNames() || [], [parser]); const propertyName = parser?.getPropertyName(); + const activeModel = parser?.getActiveModel(); + + const [selectedOption, setSelectedOption] = useState(() => { + if (activeModel) { + return selectOptions.find((opt) => opt.value === activeModel) || null; + } + return selectOptions.length > 0 ? selectOptions[0] : null; + }); + + useEffect(() => { + if (activeModel) { + const option = selectOptions.find((opt) => opt.value === activeModel); + if (option && option.value !== selectedOption?.value) { + setSelectedOption(option); + } + } else if (selectOptions.length > 0 && !selectedOption) { + setSelectedOption(selectOptions[0]); + } + }, [activeModel, selectOptions]); + const propertyHeader = propertyName ? capitalizeFirstLetter(propertyName) : propertyName; const customStyles: StylesConfig = { control: (baseStyles) => ({ @@ -20,13 +41,13 @@ export const ModelSelector = ({ }), }; - const handleChange = (selectedOption: SingleValue) => { - if (selectedOption) { - updateFormStack(selectedOption.value); + const handleChange = (newValue: SingleValue) => { + if (newValue) { + setSelectedOption(newValue); + updateFormStack(newValue.value); } }; - const activeModel = parser?.getActiveModel(); const header = propertyHeader === 'Llm' ? 'Select LLM' : `Select ${propertyHeader}`; return ( @@ -41,7 +62,7 @@ export const ModelSelector = ({ options={selectOptions} onChange={handleChange} className='pt-1 pb-1' - defaultValue={activeModel ? { value: activeModel, label: activeModel } : selectOptions[0]} + value={selectedOption} isSearchable={true} isClearable={false} styles={customStyles}