@@ -102,6 +102,10 @@ export function SearchBar<T extends string>({
102102 const [ tokenEquations , setTokenEquations ] = useState <
103103 SearchBarTokenEquation [ ]
104104 > ( [ ] ) ;
105+
106+ const [ isSuggestionsLoading , setIsSuggestionsLoading ] =
107+ useState < boolean > ( false ) ;
108+
105109 /** A ref to store the current filters to avoid reloading the token equations */
106110 const currentFilters = useRef < string | null > ( null ) ;
107111 /** A ref to store a boolean indicating if the component is updating from search */
@@ -162,27 +166,52 @@ export function SearchBar<T extends string>({
162166 [ createSuggestions ] ,
163167 ) ;
164168
169+ // Load suggestions (with proper loading tracking and cancellation)
165170 useEffect ( ( ) => {
166- async function load ( ) {
167- const params : CreateSuggestionsParams = {
168- previousToken,
169- previousEquation,
170- equationIndex : focusedTokenIndex ?. equationIndex ,
171- } ;
171+ let cancelled = false ;
172+
173+ const emptySuggestions : SearchBarSuggestions = {
174+ items : [ ] ,
175+ nature : [ ] ,
176+ type : [ ] ,
177+ } ;
172178
173- if ( usesCurrentInput && inputValue ) {
174- params . currentInput = inputValue ;
179+ const run = async ( ) => {
180+ setIsSuggestionsLoading ( true ) ;
181+ setSuggestions ( emptySuggestions ) ;
182+
183+ try {
184+ const params : CreateSuggestionsParams = {
185+ previousToken,
186+ previousEquation,
187+ equationIndex :
188+ focusedTokenIndex ?. equationIndex ?? tokenEquations . length - 1 ,
189+ } ;
190+ if ( usesCurrentInput && inputValue ) {
191+ params . currentInput = inputValue ;
192+ }
193+
194+ const result = await createSuggestions ( params ) ;
195+ if ( ! cancelled ) {
196+ setSuggestions ( result ) ;
197+ }
198+ } finally {
199+ if ( ! cancelled ) {
200+ setIsSuggestionsLoading ( false ) ;
201+ }
175202 }
203+ } ;
176204
177- const result = await createSuggestions ( params ) ;
178- setSuggestions ( result ) ;
179- }
180- load ( ) ;
205+ run ( ) ;
206+ return ( ) => {
207+ cancelled = true ;
208+ } ;
181209 } , [
182210 previousEquation ,
183211 previousToken ,
184212 createSuggestions ,
185213 focusedTokenIndex ,
214+ tokenEquations . length ,
186215 // If the current input is not used, we don't want to trigger the suggestions for each letter typed
187216 ...( usesCurrentInput ? [ inputValue ] : [ ] ) ,
188217 ] ) ;
@@ -288,6 +317,7 @@ export function SearchBar<T extends string>({
288317 setTokenEquations = { setTokenEquations }
289318 tokenEquations = { tokenEquations }
290319 suggestions = { suggestions }
320+ suggestionsLoading = { isSuggestionsLoading }
291321 focusedTokenIndex = { focusedTokenIndex }
292322 setFocusedTokenIndex = { setFocusedTokenIndex }
293323 allowKeyWordSearch = { allowKeyWordSearch }
0 commit comments