Untitled

 avatar
unknown
javascript
4 years ago
1.5 kB
3
Indexable
import React, { useState, useEffect, useCallback } from "react";

function App() {
  const [options, setOptions] = useState([]);
  const [inputValue, setInputValue] = useState("");

  const handleOnchange = (event) => {
    setInputValue(event.target.value);
  };

  const searchRequest = useCallback(async () => {
    const response = await fetch(
      `https://api.npms.io/v2/search?q=${inputValue}`
    );
    const data = await response.json();
    setOptions(data.results);
  }, [inputValue]);

  useEffect(() => {
    if (inputValue !== "") {
      let timeout = setTimeout(() => {
        searchRequest();
      }, 1500);
      return () => {
        clearTimeout(timeout);
      };
    }
  }, [inputValue, searchRequest]);

  return (
    <div
      style={{
        height: "100vh",
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
      }}
    >
      <>
        <label htmlFor="ice-cream-choice">Run da search:</label>
        <input
          value={inputValue}
          list="ice-cream-flavors"
          id="ice-cream-choice"
          name="ice-cream-choice"
          onChange={(e) => handleOnchange(e)}
        />
        <datalist id="ice-cream-flavors">
          {options?.map((option, index) => (
            <option
              key={`${option.package.name}-${index}`}
              value={option.package.name}
            />
          ))}
        </datalist>
      </>
    </div>
  );
}

export default App;
Editor is loading...