api call with every key stroke

Viewed 619

I tried to create this react website where I can search for a place. I'm having a problem cause whenever I enter a new letter in the search box, the api is called which is making the website very slow. I don't want it to call the api with every keystroke. I think this is because of the second useEffect but if I remove that useEffect then no results are displayed in the search results. How can I tackle this problem. in class component I think we can do it with componentDidUpdate but here I used useEffect but not getting the desired result.

Here's the code

App.js

  useEffect(() => {
    getItems();

    if (finalSearch) {
      filterData();
    } else {
      handleRequest();
    }
  }, [search, finalSearch]);

 
1 Answers

It looks like you call the api at the beginning and then once the search component has values, you filter the data.

If you want to stop fetching the API on each keystroke, just remove the else clause in your useEffect.

  useEffect(() => {
    getResults();

    if (finalSearch) {
      filterData();
    }
  }, [search, finalSearch]);
Related