svelte-material-ui
svelte-material-ui copied to clipboard
Unexpected behavior with async autocomplete - additional, unwanted search is run based on selection
Describe the bug
When I click on the result I want with autocomplete, it ends up running a search for the text of that result. I'm selecting objects from a list, rather than just from an array of strings.
To Reproduce
Here's my code:
<Autocomplete
search={autocomplete}
bind:value={sourcePage}
getOptionLabel={(option) =>
option ? option.title : ''}
showMenuWithNoInput={false}
label="Source page"
>
<Text
slot="loading"
style="display: flex; width: 100%; justify-content: center; align-items: center;"
>
<LinearProgress style="height: 24px" indeterminate />
</Text>
</Autocomplete>
let sourcePage: WPPage;
const searchTimer = new Timer(500); // this is a debounce
async function search(term: string) : Promise<WPPage[]> {
return new Promise((resolve, _reject) => {
searchTimer.run(async () => {
console.log("running search for", term);
const results = await runSearch(term); // this just hits a wikipedia API using fetch; nothing fancy
resolve(results);
});
});
}
async function autocomplete(term: string): Promise<WPPage[]|false> {
if (term === "") {
console.debug("blank search term");
return [];
}
console.log("searching for", term);
return search(term);
}
So you can see what's going on, I added those console logs:
searching for Autocom
running search for Autocom // this means the debounce worked
// then I clicked on the result
searching for Autocomplete
running search for Autocomplete
Expected behavior
When I select the correct value, it will be bound to the variable I set, and another search will not be run based off the text of the newly selected item.
Screenshots
https://user-images.githubusercontent.com/363720/206305091-1eb8a8b5-fbe8-4a38-b3fc-6d45b4288fa8.mp4
Desktop (please complete the following information):
- OS: Windows 11
- Browser: chrome
- Version: 108.0.5359.95 (Official Build) (64-bit) (cohort: Stable)
Additional context
When I click the result I want, it searches again - but when I click the result from the (unwanted, second) search, then it selects it properly and the menu goes away.
Update
I found this only occurs when binding to objects and using async. It works using async, as in the demo at https://sveltematerialui.com/demo/autocomplete/ , and it works using objects, as in the other demo, but when you combine the two, this bug surfaces. I'm almost positive it has to do with object equality not doing what we want 😄
In addition, even when using only strings, it still executes an additional, unwanted search, although it doesn't display the menu.
Not only async: repeated search occurs when the option is selected with a mouse click; when the keyboard is selected, everything is ok
https://user-images.githubusercontent.com/63556979/218126330-4a444689-de16-400e-a9d0-b5e3a238f18e.mp4