From 6c97e520ad9d39fb210b77e66deacdb2ab38b4a5 Mon Sep 17 00:00:00 2001 From: Alex Cernik <57844660+AlexCernik@users.noreply.github.com> Date: Thu, 28 Nov 2024 03:22:44 -0300 Subject: [PATCH] update set initial value without dataset Hi, I think it's unnecessary to check if initialValue is in initialDataSet if you're going to be calling setSelectedItem later. Try this, it will also update the selected value if a new item is added to the dataSet. For example: initialValue is null on the screen, you navigate to a screen to create an item for the dataSet, then go back to the previous screen and select the newly created item. This will select the initial item and then change if it gets updated. --- src/index.tsx | 24 ++++-------------------- 1 file changed, 4 insertions(+), 20 deletions(-) diff --git a/src/index.tsx b/src/index.tsx index e6e4b02..a9c1814 100644 --- a/src/index.tsx +++ b/src/index.tsx @@ -55,7 +55,6 @@ export const AutocompleteDropdown = memo< matchFrom, inputHeight = moderateScale(40, 0.2), suggestionsListMaxHeight = moderateScale(200, 0.2), - // bottomOffset = 0, direction: directionProp, controller, onSelectItem: onSelectItemProp, @@ -95,7 +94,6 @@ export const AutocompleteDropdown = memo< const [selectedItem, setSelectedItem] = useState(null) const [isOpened, setIsOpened] = useState(false) const initialDataSetRef = useRef(dataSetProp) - const initialValueRef = useRef(initialValueProp) const [dataSet, setDataSet] = useState(dataSetProp) const matchFromStart = matchFrom === 'start' ? true : false const { @@ -188,24 +186,10 @@ export const AutocompleteDropdown = memo< /** Set initial value */ useEffect(() => { - const initialDataSet = initialDataSetRef.current - const initialValue = initialValueRef.current - - let initialValueItem: AutocompleteDropdownItem | undefined - if (typeof initialValue === 'string') { - initialValueItem = initialDataSet?.find(el => el.id === initialValue) - } else if (typeof initialValue === 'object' && initialValue.id) { - initialValueItem = initialDataSet?.find(el => el.id === initialValue?.id) - if (!initialValueItem) { - // set the item as it is if it's not in the list - initialValueItem = initialValue - } + if (initialValueProp && typeof initialValueProp === 'object' && selectedItem?.id !== initialValueProp.id) { + setSelectedItem(initialValueProp); } - - if (initialValueItem) { - setSelectedItem(initialValueItem) - } - }, []) + }, [initialValueProp]); useEffect(() => { return () => { @@ -496,7 +480,7 @@ export const AutocompleteDropdown = memo< style={[styles.container, containerStyle]}> {}} // it's necessary use onLayout here for Androd (bug?) + onLayout={_ => { }} // it's necessary use onLayout here for Androd (bug?) style={[styles.inputContainerStyle, inputContainerStyle]}> {LeftComponent}