Autocomplete example

Abortable remote suggestions with retry.

The host debounces and cancels bounded asynchronous suggestions, rejects stale results and exposes retry. The included service is a local timer simulation with an explicit one-request failure switch.

Complete React client module · MIT · Next.js and Vite

Interactive example

Abortable remote suggestions with retry

The host debounces and cancels bounded asynchronous suggestions, rejects stale results and exposes retry. The included service is a local timer simulation with an explicit one-request failure switch.

Keyboard

  • Type at least two characters to request suggestions. Arrow Down and Enter accept a result.
  • Keep typing while a request is pending; earlier requests cannot replace newer suggestions.
  • Tab to Retry suggestions after a failure; the typed query stays intact.

States covered

  • Minimum query
  • Debounce
  • Loading
  • Request cancellation
  • Stale-result guard
  • Failure and retry
  • Bounded results

Install this complete example and its component dependencies.

Terminal
npx shadcn@latest add https://ui.bld8.dev/r/example-autocomplete-async.json
Complete source
React / TypeScript
/*!
MIT License

Copyright (c) 2026 Jaison

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
'use client';
import '@bld8/ui/styles.css';
import {useEffect,useRef,useState} from 'react';
import {Autocomplete,type AutocompleteOption} from '@bld8/ui/autocomplete';
import {Button} from '@bld8/ui';
const articles:AutocompleteOption[]=[
  {id:'tokens',label:'Design tokens',description:'Colour, spacing and type'},
  {id:'motion',label:'Motion guidelines',description:'Shared easing and reduced motion'},
  {id:'forms',label:'Form validation',description:'Native constraints and field errors'},
  {id:'keyboard',label:'Keyboard shortcuts',description:'Focus and keyboard navigation'}
];
// Replace this local simulation with a service call using the supplied signal.
function loadSuggestions(query:string,signal:AbortSignal,fail:boolean):Promise<AutocompleteOption[]>{
  return new Promise((resolve,reject)=>{
    const abort=()=>{clearTimeout(timer);reject(new DOMException('Request cancelled','AbortError'));};
    const timer=setTimeout(()=>{signal.removeEventListener('abort',abort);if(fail){reject(new Error('Suggestions could not be loaded.'));return;}resolve(articles.filter(item=>(item.label+' '+item.description).toLowerCase().includes(query.toLowerCase())).slice(0,8));},450);
    if(signal.aborted)abort();else signal.addEventListener('abort',abort,{once:true});
  });
}
export default function AsyncSuggestionsExample(){
  const [query,setQuery]=useState(''),[options,setOptions]=useState<AutocompleteOption[]>([]),[loading,setLoading]=useState(false),[error,setError]=useState(''),[attempt,setAttempt]=useState(0);
  const failNext=useRef(false),revision=useRef(0);
  useEffect(()=>{
    const request=++revision.current,controller=new AbortController();let active=true;
    setOptions([]);setError('');const text=query.trim();
    if(text.length<2){setLoading(false);return()=>{active=false;controller.abort();};}
    setLoading(true);
    const debounce=setTimeout(()=>{
      const shouldFail=failNext.current;failNext.current=false;
      loadSuggestions(text,controller.signal,shouldFail).then(items=>{if(active&&!controller.signal.aborted&&request===revision.current)setOptions(items);}).catch(reason=>{if(active&&!controller.signal.aborted&&request===revision.current)setError(reason instanceof Error?reason.message:'Suggestions could not be loaded.');}).finally(()=>{if(active&&!controller.signal.aborted&&request===revision.current)setLoading(false);});
    },200);
    return()=>{active=false;clearTimeout(debounce);controller.abort();};
  },[query,attempt]);
  return <div style={{display:'grid',gap:12}}>
    <Autocomplete label="Search help articles" value={query} onValueChange={value=>{if(value!==query)revision.current++;setQuery(value);}} options={options} filter={null} maxSuggestions={8} loading={loading} emptyText={query.trim().length<2?'Type at least two characters.':error?'Suggestions unavailable. You can keep your text.':'No articles found. You can keep your text.'} hint="The example simulates a host service. Requests are debounced, aborted and checked before results are accepted."/>
    <div style={{display:'flex',gap:8,flexWrap:'wrap'}}><Button variant="secondary" onClick={()=>{failNext.current=true;setAttempt(value=>value+1);}}>Fail next suggestion request</Button>{error&&<Button variant="secondary" onClick={()=>setAttempt(value=>value+1)}>Retry suggestions</Button>}</div>
    <p role={error?'alert':'status'} aria-label="Suggestion request status">{error|| (loading?'Loading suggestions…':query.trim().length<2?'Enter two or more characters.':options.length+' suggestions ready.')}</p>
    <p className="bui-hint">Current text: {query||'none'}</p>
  </div>;
}