Search code examples
reactjssettimeout

How to start search only when user stops typing?


I need to perform a Search when user stops typing.I know I am supposed to use setTimeout() . But with Reactjs I cant find how it works. Can someone please tell me how to invoke a method (that will handle Search) when the user stops typing for a few seconds (suppose 5).I cant figure out where to write the code to check that the user has stopped typing.

import React, {Component, PropTypes} from 'react';

export default class SearchBox extends Component {

    state={
      name:" ",
    }

    changeName = (event) => {
        this.setState({name: event.target.value}); 
    }

    sendToParent = () => {
        this.props.searching(this.state.name);
    }

    render() {
        return (
            <div>
                 <input type="text"  placeholder='Enter name you wish to Search.'  onChange={this.changeName} />

            </div>
        );
    }
}   

I want to invoke the sendToParent method when the user stops typing.


Solution

  • You can use setTimeout with respect to your code as follows,

    state = {
        name: '',
        typing: false,
        typingTimeout: 0
    }
    changeName = (event) => {
        const self = this;
    
        if (self.state.typingTimeout) {
           clearTimeout(self.state.typingTimeout);
        }
    
        self.setState({
           name: event.target.value,
           typing: false,
           typingTimeout: setTimeout(function () {
               self.sendToParent(self.state.name);
             }, 5000)
        });
    }
    

    Also, you need to bind changeName handler function in constructor.

    constructor(props) {
       super(props);
       this.changeName = this.changeName.bind(this);
    }