Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

debounced function not being called in a react component

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;
like image 233
Carl Rippon Avatar asked Jun 07 '26 15:06

Carl Rippon


1 Answers

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

raiseCriteriaChange = debounce(() => {
    this.props.onCriteriaChange(this.state.criteria);
}, 300);
like image 78
Saravana Avatar answered Jun 09 '26 03:06

Saravana



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!