0

I have a React app which fetches Github repositories with Github search API, the function looks like this;

 const searchEverything = (input: string) => {
    if (input.length > 2) {
      setSearchPageStatus(true);
      fetch(`https://api.github.com/search/repositories?q=${input}`)
        .then((res) => res.json())
        .then((data) => {
          setRepoCount(data.total_count);
          setRepos(data.items);
        });

      fetch(`https://api.github.com/search/users?q=${input}`)
        .then((res) => res.json())
        .then((data) => {
          setUserCount(data.total_count);
          setUsers(data.items);
        });
    } else {
      setSearchPageStatus(false);
    }
  };

So I get items with "onChange" attribute like this;

<input onChange={(e) => searchEverything(e.target.value)}
       type="search"
       className="header__search__input"
        placeholder="Search..."
        />

I am not getting errors or anything like that. But as you can see on each key stroke there is an API call and I feel like it's not efficent and if you have a long word there might be an error 403. So is there any better way to use this API ? The solution I thought is just putting a button and searching after click but it just takes away all the dynamism.

İlker
  • 1,872
  • 1
  • 12
  • 28
  • You can use [debounce](https://lodash.com/docs/4.17.15#debounce). Check this [post](https://stackoverflow.com/q/23123138/2873538), you will find many examples. And [this](https://stackoverflow.com/q/24004791/2873538) to understand the debounce. Here is an answer about how to not **re-create** a new [debounce](https://stackoverflow.com/a/62213046/2873538) at each render. – Ajeet Shah Mar 14 '21 at 11:15
  • Please check the preview of the 403 message if it is a authentication issue – NeERAJ TK Mar 14 '21 at 11:15
  • @İlker can you check this? – NeERAJ TK Mar 14 '21 at 14:03

1 Answers1

0

You can use throttle or debounce to limit the number of times a function is called.

You don't need to use _, can write your own if you want.

T J
  • 42,762
  • 13
  • 83
  • 138