Concept: Map pattern with fetched array data (using for loop)
Create a PokemonList component that:
https://pokeapi.co/api/v2/pokemon?limit=20results array with pokemon dataresults needs to be fetched individually (use results[i].url)Displays a list like:
Pokemon List:
- bulbasaur: height 7
- ivysaur: height 10
- venusaur: height 20
... (and more)
import { useState, useEffect } from 'react';
export default function PokemonList() {
const [pokemonList, setPokemonList] = useState([]);
useEffect(() => {
async function fetchAllPokemon() {
// Step 1: Fetch list of pokemon
const response = await fetch('https://pokeapi.co/api/v2/pokemon?limit=20');
const data = await response.json();
// Step 2: MAP: Fetch each pokemon and extract id, name, and height using for loop
const pokemonData = [];
// Your for loop here
setPokemonList(pokemonData);
}
fetchAllPokemon();
}, []);
if (pokemonList.length === 0) {
return <div>Loading...</div>;
}
return (
<div>
<h3>Pokemon List:</h3>
<ul>
{pokemonList.map((pokemon) => (
<li key={pokemon.id}>{pokemon.name}: height {pokemon.height}</li>
))}
</ul>
</div>
);
}
data.results is an arrayurl property: data.results[i].urlawait fetch(data.results[i].url)await response.json()pokemonData.push({ id: pokemon.id, name: pokemon.name, height: pokemon.height }).map() in JSX to render: pokemonList.map((pokemon) => ...)pokemon.id as the key: key={pokemon.id}Promise.all() is optional but helps with performanceimport { useState, useEffect } from 'react';
export default function PokemonList() {
const [pokemonList, setPokemonList] = useState([]);
useEffect(() => {
async function fetchAllPokemon() {
// Step 1: Fetch list of pokemon
const response = await fetch('https://pokeapi.co/api/v2/pokemon?limit=20');
const data = await response.json();
// Step 2: MAP: Fetch each pokemon and extract id, name, and height using for loop
const pokemonData = [];
for (let i = 0; i < data.results.length; i++) {
const pokemonResponse = await fetch(data.results[i].url);
const pokemon = await pokemonResponse.json();
pokemonData.push({
id: pokemon.id,
name: pokemon.name,
height: pokemon.height
});
}
setPokemonList(pokemonData);
}
fetchAllPokemon();
}, []);
if (pokemonList.length === 0) {
return <div>Loading...</div>;
}
return (
<div>
<h3>Pokemon List:</h3>
<ul>
{pokemonList.map((pokemon) => (
<li key={pokemon.id}>{pokemon.name}: height {pokemon.height}</li>
))}
</ul>
</div>
);
}
data.results array using a for loop{ id: ..., name: ..., height: ... }pokemonData.push({ id: pokemon.id, name: pokemon.name, height: pokemon.height }).map() method: Transform array items into JSX elements for displaypokemonList.map((pokemon) => <li key={pokemon.id}>...</li>).map() method is the built-in JavaScript way to do the map patternkey={index} works, it’s not ideal because:
key={pokemon.id} is better because:
Note: Learn more about the built-in .map() method at MDN: Array.map()
Try:
limit=20 to limit=50