3

I have the react component below. The raiseCriteriaChange method is called but the this.props.onCriteriaChange(this.state.criteria) line is never reached.

Any ideas why the code never reaches this.props.onCriteriaChange?

import * as React from 'react';
import { debounce } from 'lodash';

interface CustomerSearchCriteriaProps {
  onCriteriaChange: (criteria: string) => void;
}
interface CustomerSearchCriteriaState {
  criteria: string;
}

class CustomerSearchCriteria extends React.Component<CustomerSearchCriteriaProps, CustomerSearchCriteriaState> {

  constructor() {
    super();

    this.state = {
      criteria: ''
    };
  }

  // problem method:
  raiseCriteriaChange = () => {
    // the call reaches here fine ...
    debounce(
    () => {
       // ... but the call never reaches here ... why is this?
       this.props.onCriteriaChange(this.state.criteria);
    },  
    300);
  }

  handleCriteriaChange = (e: React.FormEvent<HTMLInputElement>) => {
    this.setState({ criteria: e.currentTarget.value }, () => {
      this.raiseCriteriaChange();
    });
  }

  render() {

    return (
      <div className="input-group">
        <input
          type="text" 
          value={this.state.criteria} 
          onChange={this.handleCriteriaChange} 
          className="form-control"
        />
      </div>
    );
  }
}

export default CustomerSearchCriteria;
Carl Rippon
  • 4,553
  • 8
  • 49
  • 64
  • Possible duplicate of [Using jQuery $(this) with ES6 Arrow Functions (lexical this binding)](https://stackoverflow.com/questions/27670401/using-jquery-this-with-es6-arrow-functions-lexical-this-binding) – InQβ Aug 25 '17 at 05:25

2 Answers2

4

_.debounce simply returns a function that must be called. Try changing your code like:

raiseCriteriaChange = debounce(() => {
    this.props.onCriteriaChange(this.state.criteria);
}, 300);
Saravana
  • 37,852
  • 18
  • 100
  • 108
2

See _.debounce, which says it

(Function): Returns the new debounced function.

so you need to call it like

var debounced = debounce(
    () => {
       // ... but the call never reaches here ... why is this?
       this.props.onCriteriaChange(this.state.criteria);
    },  
    300
);

debounced();
leaf
  • 1,624
  • 11
  • 16