Necesito realizar una búsqueda cuando el usuario deja de escribir. Sé que se supone que debo usar setTimeout() . Pero con Reactjs no puedo encontrar cómo funciona. ¿Puede alguien decirme cómo invocar un método (que manejará la búsqueda) cuando el usuario deja de escribir durante unos segundos (supongamos que 5)? No sé dónde escribir el código para comprobar que el usuario ha dejado de escribir.
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> ); } }Quiero invocar el método sendToParent cuando el usuario deja de escribir.
Implementar usando el gancho useEffect:
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)} /> ) }Puede usar setTimeout con respecto a su código de la siguiente manera,
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) }); } Además, debe vincular changeName de controlador de cambio de nombre en el constructor.
constructor(props) { super(props); this.changeName = this.changeName.bind(this); }Otra forma que funcionó conmigo:
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> ); } }