TechnoCorner
TechnoCorner

Reputation: 5145

React Throttle does not work

I'm a newbie to react and I'm trying to do a "Search" and I'm trying throttle the input. But it doesn't work. Please kindly correct me where i'm doing wrong?

 render() {
    const { value, suggestions } = this.state;
    const inputProps = {
      placeholder: 'Try me! Search for iPad, iPhone',
      value,
      onChange: throttle(150, this.onChange), //DOESNT WORK :(
    };

    return (
      <Row>
        <Col grow={false} padding={0}>
          <i className='ion-ios-search-strong'></i>
        </Col>
        <Col padding={0}>
          <Autosuggest suggestions={suggestions}
              onSuggestionsUpdateRequested={this.onSuggestionsUpdateRequested}
              getSuggestionValue={this.getSuggestionValue}
              renderSuggestion={this.renderSuggestion}
              inputProps={inputProps} />
        </Col>
      </Row>
    );
  }

  onChange(event, { newValue }) {

    //_.throttle( () => {  this.getValue(newValue) } , 500 );  //DOESNT WORK EITHER :(

    this.getValue(newValue);

    this.setState({
      value: newValue
    });
  }

Upvotes: 1

Views: 1632

Answers (1)

Garry Taylor
Garry Taylor

Reputation: 1115

It's very difficult without knowing the library you're using to throttle but my guess is that the following is running the throttle function and storing the results in the "onChange" method. Probably not what you want to do.

onChange: throttle(150, this.onChange)

If you did the following it may work

onChange: () => throttle(150, this.onChange)

Another option is to create a helper function and call that, doing the binding in the constructor to wire it all up correctly.

constructor() {
   super();
   this.onChange = this.onChangeWorker.bind(this);
}

onChangeWorker() {
   throttle(150, () => {
      // do work
   }
}

If this is still not working, have a look at the following. https://www.npmjs.com/package/react-throttle

Upvotes: 1

Related Questions