Skip to content

Instantly share code, notes, and snippets.

@harrisonmalone
Created October 2, 2019 11:14
Show Gist options
  • Select an option

  • Save harrisonmalone/edba3be0b5d48dd317296ed8d19d783c to your computer and use it in GitHub Desktop.

Select an option

Save harrisonmalone/edba3be0b5d48dd317296ed8d19d783c to your computer and use it in GitHub Desktop.
using react hooks
import React, { useState, useEffect } from 'react';
import axios from 'axios';
function App() {
// same as setting up state
const [count, setCount] = useState(0)
const [pokemon, setPokemon] = useState([])
// same as componentDidMount
useEffect(() => {
if (pokemon.length === 0) {
getPokemonData();
}
});
// onclick method
const addToCount = () => setCount(count + 1)
const renderPokemon = () => {
return pokemon.map((poke, index) => {
return (
<li key={index}><img src={poke.picture} alt={poke.name} height="100" width="100"/>{poke.name}</li>
)
})
}
const addEachPokemon = (response) => {
return response.data.results.map(async (poke) => {
const response = await axios.get(poke.url)
const picture = response.data.sprites.front_default
poke.picture = picture
return poke
})
}
const getPokemonData = async () => {
const response = await axios.get("https://pokeapi.co/api/v2/pokemon")
const pokemonPromises = await addEachPokemon(response);
const newPokemon = await Promise.all(pokemonPromises)
setPokemon(newPokemon)
}
if (!pokemon) {
return null
} else {
return (
<>
<h1 onClick={addToCount}>{count}</h1>
{renderPokemon()}
</>
)
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment