AutoComplete ComboBox with remote data (Fluent UI v9 React Components)
In a recent project I had the challenge to find a way to load data for a Fluent React UI v9 ComboBox dynamically. But due to the data amount I could not load all data at once. I had to wait after the user entered some text in the ComboBox. I had to use the the entered text as filter value for the REST call - like ?$filter=contains(...)
To solve this I hooked into the "onChange" CombBox event. When the user is entering text, I use the text and call a REST endpoint to fetch the data. The following code snippets shows the main implementation:
return ( <div className={styles.root}> <label id={comboId}>Account</label> <Combobox onOptionSelect={onOptionSelect} aria-labelledby={comboId} placeholder="Select a user" onChange={async (ev) => { // You can change the check of length and start later - e. g. after 3 chars if (ev.target.value.length > 0) { setQuery(ev.target.value); const response = await fetch( `https://services.odata.org/TripPinRESTierService/(S(tymecmt5j4w51s3w2y5uzuum)) /People?$filter=contains(LastName,'${ev.target.value}')` ); const body = await response.json(); const mapped = body.value.map((n: any) => { return { children: n.LastName+", "+n.FirstName, value: n.keyField }; }); setOptions(mapped); } else setQuery(ev.target.value); }} value={query} > {options.map((element:any) => ( <Option key={element.id}> {element.children} </Option> ))} </Combobox> </div> );
I have prepared a simple stackblitz to demonstrate the implementation: Stackblitz

Kommentare