react-select: Using debounce on loadOptions doesn't always show results
When I use lodash’s debounce on my loadOptions handler, typing doesn’t behave consistently (results are missing, spinner is showing indefinitely) for certain inputs.
When the debounce is removed (and requests are fired for every keystroke), options are consistently shown. I’ve also tried setting cache={false} to no avail.
Sample here: https://codesandbox.io/s/xplr0lly8w
To see this weird behavior, type a few letters of a github username into the text input. Observe it not really-but-sort-of-working.
To see it working consistently, remove this.getUsers = _.debounce(this.getUsers, 250); in the constructor.
This occurs on react-select 1.2.1. Let me know if you need any more info to repro.
Also just wanted to say you guys and gals are doing great work!
About this issue
- Original URL
- State: closed
- Created 6 years ago
- Comments: 17 (3 by maintainers)
I managed to find a way to avoid the weird behaviour, here is a sandbox.
I don’t know if this is the desired result, but I thought I would share it just in case.
I think you need to use the callback option instead of returning a promise if you use debounce.
I changed your example in this snippet and it now works: https://codesandbox.io/s/mm16n2x5k9
@ADTC Sorry you had difficulty with this, I understand that the docs are less than ideal. Generally, react-select should own as little of the implementation detail as possible. The debounce solution for one situation may not be appropriate for another; in cases like this it’s often good to make the API flexible so the consumer can implement whatever they need e.g. just provide a
loadOptionscallback—the composition of that function is up to the author who has the most context about the application’s requirements.@jossmac is it possible to enhance the documentation with a verified official method to do debouncing correctly with
loadOptions? Because I had found it a struggle to piece everything together using this issue and the sparse documentation.Here’s the modified CodeSandbox, updated to the latest versions of dependencies: https://codesandbox.io/s/laughing-margulis-rb5tsu?file=/src/index.js
Apparently it so happened that in our actual project, we’re using
react-select-async-paginatewhich doesn’t support any callbacks. However, it has a much easier fix: simply add a prop calleddebounceTimeoutand give it a number in milliseconds.I wish
react-selectitself has a similar prop so we don’t need to implement debouncing ourselves.@JonathanWbn that seems to work 🎉 - there’s a subtle difference between how you call the debounced method (your method calls a debounced fetch) vs how I’m doing it (I change the method passed to
loadOptionsto be debounced itself and then pass it toreact-select).Do you know why this works? If I can grok this, I’d be happy to update the docs so this is clear (unless this is a bug…?)