-
-
Save interlark/2463d8f5e5f20b284a2687f561f2a9e3 to your computer and use it in GitHub Desktop.
Revisions
-
Simon Willison created this gist
Mar 16, 2018 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,56 @@ # React debouncing pattern for API calls Classic debounce function: const debounce = (fn, delay) => { let timer = null; return function (...args) { const context = this; timer && clearTimeout(timer); timer = setTimeout(() => { fn.apply(context, args); }, delay); }; } A component that performs API calls on textinput change: class PlaceSearch extends Component { state = { q: '', places: [], } fetchPlaces(q) { get(`http://www.example.com/places/`, { params: {q} }).then(response => { this.setState({places: response.data.places}); }); } constructor(props) { super(props); this.fetchPlaces = debounce(this.fetchPlaces, 200); } onSearchChange(ev) { const q = ev.target.value; this.setState({q: q}); this.fetchPlaces(q); } render() { return ( <div> <input type="text" value={this.state.q} onChange={this.onSearchChange.bind(this)} placeholder="Search for a place" /> {this.state.places.map(place => ( <div key={place.id} className="placePick"> <a href={`?place_id=${place.id}`}>{place.name}</a> </div> ))} </div> ); } }