I'm using react-select loading the results from an api and debouncing the queries with lodash.debounce:
import React, {useState} from 'react';
import AsyncSelect from 'react-select/lib/Async';
import debounce from 'lodash.debounce';
import {search} from './api';
const _loadSuggestions = (query, callback) => {
return search(query)
.then(resp => callback(resp));
};
const loadSuggestions = debounce(_loadSuggestions, 300);
function SearchboxTest() {
const [inputValue, setInputValue] = useState("");
const onChange = value => {
setInputValue(value);
};
return (
<AsyncSelect
value={inputValue}
loadOptions={loadSuggestions}
placeholder="text"
onChange={onChange}
/>
)
}
It seems to work fine when I enter something in the searchbox for the first time (query is debounced and suggestions populated correctly), but if I try to enter a new value, a second fetch query is fired as expected, but the suggestions coming from that second call are not displayed (and I don't get the "Loading..." message that react-select displays).
When I don't debounce the call the problem seems to go away (for the first and any subsequent calls):
import React, {useState} from 'react';
import AsyncSelect from 'react-select/lib/Async';
import {search} from '../../api';
const loadSuggestions = (query, callback) => {
return search(query)
.then(resp => callback(resp));
};
function SearchboxTest() {
const [inputValue, setInputValue] = useState("");
const onChange = value => {
setInputValue(value);
};
return (
<AsyncSelect
value={inputValue}
loadOptions={loadSuggestions}
placeholder="text"
onChange={onChange}
/>
)
}
Any idea what is going on? Any help to understand this issue would be much appreciated.
M;
I was aslo facing the same issue and got this solution.
If you are using callback function, then You DON'T need to return the result from API.
Try removing return keyword from _loadSuggestions function. as shown below
import React, {useState} from 'react';
import AsyncSelect from 'react-select/lib/Async';
import debounce from 'lodash.debounce';
import {search} from './api';
const _loadSuggestions = (query, callback) => {
search(query)
.then(resp => callback(resp));
};
const loadSuggestions = debounce(_loadSuggestions, 300);
function SearchboxTest() {
const [inputValue, setInputValue] = useState("");
const onChange = value => {
setInputValue(value);
};
return (
<AsyncSelect
value={inputValue}
loadOptions={loadSuggestions}
placeholder="text"
onChange={onChange}
/>
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With