async react-select fetching on every keystroke
See original GitHub issueI love the ease of styling and functionality of react select. Props to you guys for doing an excellent job.
Recently I was requested to add an async option where I would fetch options if the option list amount was greater than 20 (all handled in the backend). I found it works great! However, the axios call is firing on every keystroke.
I’ve tried long and dead hours to figure this out. I’m almost there, but I’m stuck on this.
oncall is defined before the definition of the function component as oncall = false.
const promiseOptions = input =>
new Promise( resolve => {
setTimeout( () => {
if (!oncall) {
oncall = true;
resolve(
axios.get(optionsUrl)
.then((response) => {
console.log(response)
oncall = false;
return response.data.data.filter(i => i.label.toLowerCase().includes(input));
})
.catch((error) => {
console.log(error);
})
);
}
}, 1000);
});
This code works sometimes. It would be great if I can start a call after entering 3 letters, set a timer to call again only after the user has stopped typing for 1 second. I’ve managed to do this with ‘onkeyup’ on another search input in my app that doesn’t use react-select. This plugin lacks the ‘onkeyup’ prop. I’ve also tried with settimeout without avail.
I appreciate any help.
Issue Analytics
- State:
- Created 3 years ago
- Comments:5 (1 by maintainers)
Top GitHub Comments
I expected react-select async to have some sort of “cooldown” parameter to prevent browser from firing too many xhr requests. For better workarounds check #614 .
The best solution I found was @ebonow 's codesandbox, linked in #614 : https://codesandbox.io/s/react-select-async-debounce-usecallback-oeixm
The devs should include a note in the docs addressing this issue, as including this feature in the library might be quite complex.
Agreed. I have a point in the open docs improvement thread for this among a few other things that could use more visibility… https://github.com/JedWatson/react-select/issues/3006#issuecomment-761839076