From f16a2c9564490a898fd3bb3f69753597442572d4 Mon Sep 17 00:00:00 2001 From: p-sw Date: Sat, 8 Jun 2024 05:05:20 +0900 Subject: [PATCH] refactor(cli): optimize SearchBox setState calls State setting logic for SearchBox in the CLI package has been streamlined. Redundant setState calls have been eliminated while others are more appropriately placed for better state management. This refactor focuses on the selected and queryMode states. Improved handling of selection state enhances component efficiency. --- packages/cli/src/components/SearchBox.tsx | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/packages/cli/src/components/SearchBox.tsx b/packages/cli/src/components/SearchBox.tsx index de86ff1..eb96d65 100644 --- a/packages/cli/src/components/SearchBox.tsx +++ b/packages/cli/src/components/SearchBox.tsx @@ -23,7 +23,7 @@ export function SearchBox({ const [queryMode, setQueryMode] = useState(true) const [isLoading, setLoading] = useState(false) const [suggestions, setSuggestions] = useState([]) - const [selected, setSelected] = useState(0) + const [selected, setSelected] = useState(-1) useEffect(() => { if (queryMode) { @@ -33,10 +33,7 @@ export function SearchBox({ query, ).then((result) => { setSuggestions(result) - setLoading(false) - if (result.length <= selected) { - setSelected(result.length - 1) - } + setSelected(-1) }) } }, [query, queryMode]) @@ -46,10 +43,6 @@ export function SearchBox({ const found = components.find(({key}) => key === suggestions[selected]) found && onChange(found) } - if (suggestions[selected]) { - setQueryMode(false) - setQuery(suggestions[selected] ?? '') - } }, [selected, suggestions, onChange]) const app = useApp() @@ -57,13 +50,21 @@ export function SearchBox({ useInput((i, k) => { if (k.downArrow) { setSelected((p) => (p >= suggestions.length - 1 ? 0 : p + 1)) + setQueryMode(false) } if (k.upArrow) { setSelected((p) => (p <= 0 ? suggestions.length - 1 : p - 1)) + setQueryMode(false) } onKeyDown?.(i, k, app) }) + useEffect(() => { + if (!queryMode && suggestions[selected]) { + setQuery(suggestions[selected]) + } + }, [queryMode, selected]) + return ( {helper}