Skip to content Skip to sidebar Skip to footer

Execute Api Request When User Stops Typing Search Box

I'm building a search field that is fetching from a data base upon users input and I'm struggling a bit. At the moment, it is fetching data in every keystroke, which is not ideal.

Solution 1:

You really just need to debounce your input's onChange handler, or better, the function that is actually doing the asynchronous work.

Very simple debouncing higher order function:

constdebounce = (fn, delay) => {
  let timerId;
  return(...args) => {
    clearTimeout(timerId);
    timerId = setTimeout(() =>fn(...args), delay);
  }
};

Example Use:

fetchData = debounce(() => fetch(.....).then(....), 500);

componentDidUpdate(.......) {
  // input value different, call fetchData
}

<Input
  toolbar
  elementType={this.props.inputC.elementType}
  elementConfig={this.props.inputC.elementConfig}
  value={this.props.inputC.value}
  changed={this.props.onChangedHandler}
/>

Demo Code

Edit execute-api-request-when-user-stops-typing-search-box

constdebounce = (fn, delay) => {
  let timerId;
  return(...args) => {
    clearTimeout(timerId);
    timerId = setTimeout(fn, delay, [...args]);
  };
};

constfetch = (url, options) => {
  console.log("Fetching", url);
  returnnewPromise((resolve) => {
    setTimeout(() => {
      console.log("Fetch Resolved");
      resolve(`response - ${Math.floor(Math.random() * 1000)}`);
    }, 2000);
  });
};

exportdefaultclassAppextendsComponent {
  state = {
    search: "",
    response: ""
  };

  changeHandler = (e) => {
    const { value } = e.target;
    console.log("search", value);
    this.setState({ search: value });
  };

  fetchData = debounce(() => {
    const { search } = this.state;
    const query = search.length ? `?orderBy="country"&equalTo="${search}"` : "";

    fetch(
      "https://react-hooks-update.firebaseio.com/ingredients.json" + query
    ).then((response) =>this.setState({ response }));
  }, 500);

  componentDidUpdate(prevProps, prevState) {
    if (prevState.search !== this.state.search) {
      if (this.state.response) {
        this.setState({ response: "" });
      }
      this.fetchData();
    }
  }

  render() {
    const { response, search } = this.state;
    return (
      <divclassName="App"><h1>Hello CodeSandbox</h1><h2>Start editing to see some magic happen!</h2><label>
          Search
          <inputtype="text"value={search}onChange={this.changeHandler} /></label><div>Debounced Response: {response}</div></div>
    );
  }
}

Post a Comment for "Execute Api Request When User Stops Typing Search Box"