Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

96
Visualizações
How to make a search on an API?

I'm trying to implement search functionality on the Pokemon API, I have tried different methods but I cannot make it work for some reason.

My idea was to make a function that handles the changes on the event and then pass that to a hook(useState) and maybe make a get request and rerender?

I have this method for getting all Pokemons from the API. Should I make a new designed to filter the request?


export async function getAllPokemon(url) {
    return new Promise((resolve) => {
        fetch(url).then(res => res.json())
            .then(data => {
                resolve(data)
            })
    });
}

function App() {

  ....
  const [filter, setFilter] = useState("");

  function handleChange(event) {
    setOption(event.target.value)
    console.log(option)
  }

  const initialURL = `https://pokeapi.co/api/v2/pokemon?limit=50`

  const handleSearchChange = (e) => {
    setFilter(e.target.value);

  };

  useEffect(() => {
    async function fetchData() {
      let response = await getAllPokemon(initialURL)
      await loadPokemon(response.results);
      setLoading(false);
    }
    fetchData();
  }, [option])


  const loadPokemon = async (data) => {
    let _pokemonData = await Promise.all(data.map(async pokemon => {
      let pokemonRecord = await getPokemon(pokemon)
      return pokemonRecord

    }))
    setPokemonData(_pokemonData);

  }

  return (
    <>
      <div >
        <div>
          <input
            type="text"
            id="header-search"
            placeholder="Search Pokemon"
            name="s"
            onChange={handleSearchChange}
          />
          <button >Search</button>
        </div>
      </div>
      <div>
        {loading ? <h1 style={{ textAlign: 'center' }}>Loading...</h1> : (
          <>        
            <div className="grid-container">
              {pokemonData.map((pokemon) => {
                return <Card pokemon={pokemon} />
              })}
            </div>
            
          </>
        )}
      </div>
    </>
  );
}

export default App;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You need to filter the array of Pokemon's that you are getting in your onChange. So something like

onChange = e = > {
      setPokemons(pokemons.filter(pokemon => pokemon.indexOf(e.target.value) > -1))
}

So, this will toggle your local state variable that you are rendering on every key that is typed, which in turn will filter your array.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda