How to start search only when user stops typing?

后端 未结 10 1775

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

相关标签:
10条回答
  • 2020-12-07 19:09

    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);
    }
    
    0 讨论(0)
  • 2020-12-07 19:09

    Implement using useEffect hook:

    function Search() {
      const [searchTerm, setSearchTerm] = useState('')
    
      useEffect(() => {
        const delayDebounceFn = setTimeout(() => {
          console.log(searchTerm)
          // Send Axios request here
        }, 3000)
    
        return () => clearTimeout(delayDebounceFn)
      }, [searchTerm])
    
      return (
        <input
          autoFocus
          type='text'
          autoComplete='off'
          className='live-search-field'
          placeholder='Search here...'
          onChange={(e) => setSearchTerm(e.target.value)}
        />
      )
    }
    
    0 讨论(0)
  • 2020-12-07 19:14

    Here's a working component template with some useful parameters to get your started.

    import React, { Component } from 'react'
    
    const initialState = { results: [], value: '' }
    
    export default class SearchBox extends Component {
      state = initialState
      timeout = null
      search_url = "https://example.com/search?q="
      min_query_length = 2
      timeout_duration = 300
    
      handleSearchChange = (e) => {
        let value = e.target.value
        clearTimeout(this.timeout);
        if (value.length < 1) {
            return this.setState(initialState) 
        } else {
            this.setState({ value })
            if (value.length>=this.min_query_length) {    
                this.timeout = setTimeout(this.search, this.timeout_duration);
            }
        }
      }
    
      search = () => {
        // assuming your results are returned as JSON
        fetch(`${this.search_url}${this.state.value}`)
        .then(res => res.json())
        .then(data => {
            this.setState({
                results: data,
            })
        })
      }
    
      render() {
        return (
              <input
                onChange={this.handleSearchChange}
              />
        )
      }
    }
    
    
    0 讨论(0)
  • 2020-12-07 19:15

    Another way that worked with me:

    class Search extends Component {
      constructor(props){
        super(props);
        this.timeout =  0;
      }
    
      doSearch(evt){
        var searchText = evt.target.value; // this is the search text
        if(this.timeout) clearTimeout(this.timeout);
        this.timeout = setTimeout(() => {
          //search function
        }, 300);
      }
    
       render() {
        return (
          <div className="form-group has-feedback">
            <label className="control-label">Any text</label>
            <input ref="searchInput" type="text" onChange={evt => this.doSearch(evt)} />
          </div>
        );
      }
    }
    
    0 讨论(0)
提交回复
热议问题