Untitled

mail@pastecode.io avatar
unknown
javascript
2 years ago
1.8 kB
1
Indexable
Never
import React, { useCallback, useState } from "react";

const debounce = (func, wait) => {
  let timeout;
  return function (...args) {
    const context = this;
    if (timeout) clearTimeout(timeout);
    timeout = setTimeout(() => {
      timeout = null;
      func.apply(context, args);
    }, wait);
  };
};

const getSearchSuggestions = async (val) => {
  const response = await fetch("https://api.npms.io/v2/search?q=" + val);
  const data = await response.json();
  return data;
};

function App() {
  const [inputText, setInputText] = useState("");
  const [searchSuggestions, setSearchSuggestions] = useState([]);

  const debounceSearchRequest = useCallback(
    debounce(async (value) => {
      const { results } = await getSearchSuggestions(value);
      return setSearchSuggestions(results);
    }, 1000),
    []
  );

  function onInputChangeHandler(e) {
    setInputText(e.target.value);
    debounceSearchRequest(e.target.value);
  }

  return (
    <div
      className="App"
      style={{
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        height: "100vh",
      }}
    >
      <label htmlFor="search-input">Search:</label>
      <input
        id="search-input"
        name="search-input"
        role="searchbox"
        list="searchSuggestions"
        onChange={onInputChangeHandler}
        value={inputText}
      />
      <datalist id="searchSuggestions">
        {searchSuggestions.length > 0 &&
          searchSuggestions.map((suggestion, index) => {
            return (
              <option
                value={suggestion.package.name}
                key={"suggestion.package.name" + index}
              ></option>
            );
          })}
      </datalist>
    </div>
  );
}

export default App;