I have the following onChange function
onChange = e => {
this.setState({
autocompleteValues: [],
showPredictivo: true
})
if (e.target.value.length > 3) this.partialSearch(e.target.value) //this is the one im concerned about
this.setState({ value: e.target.value, hasError: false, errorMsg: this.state.errorMsgSafe });
if (this.props.validateOn && (this.props.validateOn === undefined || this.props.validateOn === "onChange")) {
this.validaciones();
};
};
That function partialSearch
will only trigger when the value length is more than 3, but i want to add another condition, and its to trigger it only if the value hasnt changed in the past 300ms.
How would i do that there?
EDIT: I have tried to add a debounce / throttle but it doesnt seem to work at all, the function is never triggered
This is my whole code
async partialSearch(searchTerm?: string) {
const environment = process.env.REACT_APP_ENV ? process.env.REACT_APP_ENV : "pre";
const api = process.env.REACT_APP_API ? process.env.REACT_APP_API : "my_api";
const api_version = "v2";
let baseUrl = getBaseUrl(api, environment) + "/search?q=" + searchTerm
return fetchSPA(baseUrl, undefined, { version: api_version })
.then(res => {
if (res && res.data && res.data.length) {
const firstFive = res.data[0].resultSearch?.cars.slice(0, 5).map(val => {
return { denominacion: val.denominacion, plate: val.id };
})
if (firstFive !== undefined) this.setState({ autocompleteValues: firstFive })
}
}).catch((res) => {
console.log("Error Fetch:: ", res)
});
}
onChange = e => {
this.setState({
autocompleteValues: [],
showPredictivo: true
})
if (e.target.value.length > 3) _.debounce(() => this.partialSearch(e.target.value), 300)
this.setState({ value: e.target.value, hasError: false, errorMsg: this.state.errorMsgSafe });
if (this.props.validateOn && (this.props.validateOn === undefined || this.props.validateOn === "onChange")) {
this.validaciones();
};
};
The component where its called
Without the debounce/throttle it works, but when adding it, its never triggered
<SCInput
type={type || "text"}
id={id ? id : null}
name={name}
disabled={disabled}
readOnly={readOnly}
style={style}
hasError={errorMsg ? true : false}
compact={compact}
onChange={onChange}
onBlur={onBlur}
placeholder={placeholder}
value={this.state.value}
>