Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input doesn't work when used with debounce, event.persist() and storing value at parent component

I need an input field with debounced search and value should be passed from parent component. But it doesn't work when value passed from parent component. What is the right way to implement it?

Codesandbox example https://codesandbox.io/embed/debounce-input-owdwj

Text field with debouncing

class MyTextField extends Component {
  search = _.debounce(event => {
    this.props.onChange(event.target.value);
  }, 300);

  handleChangeInput = event => {
    event.persist();

    this.search(event);
  };

  render() {
    return (
      <TextField
        value={this.props.value}
        placeholder="type"
        onChange={this.handleChangeInput}
      />
    );
  }
} 

Parent component storing the value of text field

class Form extends Component {
  state = {
    value: ""
  };

  handleChangeInput = value => {
    this.setState({
      value
    });
  };

  render() {
    return (
      <div>
        <h2>{this.state.value}</h2>
        <MyTextField
          value={this.state.value}
          onChange={this.handleChangeInput}
        />
      </div>
    );
  }
}

2 Answers

The problem here is that you are updating the component only after 300 seconds which will not update the input box also. first, you need to update the search box component whenever there is a keyup and later parent can be informed about the changed after 300 seconds I have updated your code reference please check it out https://codesandbox.io/embed/debounce-input-gm50t

like image 147
jaswanth Avatar answered Oct 19 '25 02:10

jaswanth


Declare your debounce function in componentDidMount is everything will be fine.

1) Without state

class MyTextField extends Component {
  handleChangeInput = e => {
    this.search(e.target.value)
  };

  componentDidMount() {
    this.search =_.debounce((value) => {
      this.props.onChange(value);
    }, 300)
  }

  render() {
    return (
      <TextField
        value={this.props.value}
        placeholder="type"
        onChange={this.handleChangeInput}
      />
    );
  }
}

export default MyTextField;

2) With state:

class MyTextField extends Component {
  state = {
    textValue: ''
  }

  handleChangeInput = e => {
    this.setState({
      textValue: e.target.value
    }, () => { this.search()})
  };

  componentDidMount() {
    this.search =_.debounce(() => {
      this.props.onChange(this.state.textValue);
    }, 300)
  }

  render() {
    return (
      <TextField
        value={this.props.value}
        placeholder="type"
        onChange={this.handleChangeInput}
      />
    );
  }
}

export default MyTextField;

Hope that helps!!!

like image 21
tarzen chugh Avatar answered Oct 19 '25 01:10

tarzen chugh



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!