Skip to content

Instantly share code, notes, and snippets.

@sohammondal
Forked from simonw/react-debouncing.md
Created April 12, 2020 03:45
Show Gist options
  • Save sohammondal/33bd1d8cd92f155489dd84ac9de0b874 to your computer and use it in GitHub Desktop.
Save sohammondal/33bd1d8cd92f155489dd84ac9de0b874 to your computer and use it in GitHub Desktop.
React debouncing pattern for API calls

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>
        );
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment