How to start search only when user stops typing?

后端 未结 10 1780

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

    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 (
         setSearchTerm(e.target.value)}
        />
      )
    }
    

提交回复
热议问题