NyaSol
NyaSol

Reputation: 567

how to handle change on the input field,and debounce function reactjs

I want to be able to change the value attribute inside an input tag dynamically but also to set the initial value to some text

I would like to send an API request only after the user stopped typing, therefore I'm using a debounce function, the problem is I'm not able to keep updating the input field as the user type.

class App extends React.Component {
  static propTypes = {
  };

  constructor() {
    super();
    this.state = {
      tag: 'art',
      searchTerm: 'art'

    };
  }

  callApi = debounce ((searchTerm) =>{
        this.setState({searchTerm:searchTerm});
  },5000) 

  onSearchHandler = searchTerm =>{
    this.setState({tag:searchTerm})
    this.callApi(searchTerm)
  }


  render() {
    return (
      <div className="app-root">
        <div className="app-header"> 
          <h2>Flickr Gallery</h2>
          <input 
              className="app-input" 
              onChange={event => {this.onSearchHandler(event.target.value)}}
              value ={this.state.tag}
              />
        </div>
        <Gallery tag={this.state.searchTerm}/>
      </div>
    );
  }
}

if I'll delete the value attribute from the input field then everything is fine, so how can I add the value attribute and still change it on demand, but send the request only after X Seconds?

Upvotes: 0

Views: 2099

Answers (1)

smashed-potatoes
smashed-potatoes

Reputation: 2222

It appears that you are debouncing the update of your state when you only want to debounce the api request. You will want to always update your state on change and then debounce your api request. e.g.:

callApi = debounce(() => {
  /** your API call */
}, 5000)

onSearchHandler = searchTerm => {
  this.setState({ tag:searchTerm });
  this.callApi();
}

The reason is because by setting/updating the value based on state you have created a controlled component (see the React Controlled Components documentation for more details) and you were debouncing the updating of its value.

Upvotes: 2

Related Questions