0

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}

                        >
mouchin777
  • 1,428
  • 1
  • 31
  • 59
  • 2
    what about debounce? – Roy.B Dec 22 '20 at 09:16
  • @Roy.B im trying to implement it but so far crashing ``` if (e.target.value.length > 3) _.debounce(this.partialSearch(e.target.value), 300)``` Debounce Expected a function – mouchin777 Dec 22 '20 at 09:29
  • 1
    @mouchin777 try using `() => this.partialSearch(e.target.value)` as the first parameter to `debounce`, which wraps the `partialSearch` call in a function. Otherwise, you're passing the output of `partialSearch` instead of a function. – aryanm Dec 22 '20 at 09:32
  • https://stackoverflow.com/questions/47809666/lodash-debounce-not-working-in-react fixed it thanks to this – mouchin777 Dec 22 '20 at 10:01

1 Answers1

0

You're most likely looking for a debounce / throttle here. This article explains the scenario: https://css-tricks.com/debouncing-throttling-explained-examples/.

In short, by debouncing, you're wrapping a function over the function which gets called often. The "wrapper"-function is making sure, that the function inside only gets called again after a certain time has passed.

An easy way to implement this is to use a utility-library like lodash or you could google for a fitting debounce-function.

foxxycodes
  • 233
  • 2
  • 6