Concept: Map pattern with fetched data (using for loop)
Create a PokemonMoves component that:
https://pokeapi.co/api/v2/pokemon/pikachuuseEffect to extract all move names from the pokemon.map() in JSX to display all moves as a listWhen loaded, displays all move names:
Moves:
- thunder-shock
- quick-attack
- thunderbolt
- ... (and more)
import { useState, useEffect } from 'react';
export default function PokemonMoves() {
const [moveList, setMoveList] = useState([]);
useEffect(() => {
async function fetchPokemon() {
const response = await fetch('https://pokeapi.co/api/v2/pokemon/pikachu');
const data = await response.json();
// MAP: Use for loop to extract move names
const moveNames = [];
// Your for loop here
setMoveList(moveNames);
}
fetchPokemon();
}, []);
if (moveList.length === 0) {
return <div>Loading...</div>;
}
return (
<div>
<h3>Moves:</h3>
<ul>
{moveList.map((move) => (
<li key={move}>{move}</li>
))}
</ul>
</div>
);
}
moves array{ move: { name: 'thunder-shock' } }useEffect: for (let i = 0; i < data.moves.length; i++)data.moves[i].move.namemoveNames.push(data.moves[i].move.name).map() in JSX to render: moveList.map((move) => ...)move as the key: key={move} (each move name is unique for this pokemon)import { useState, useEffect } from 'react';
export default function PokemonMoves() {
const [moveList, setMoveList] = useState([]);
useEffect(() => {
async function fetchPokemon() {
const response = await fetch('https://pokeapi.co/api/v2/pokemon/pikachu');
const data = await response.json();
// MAP: Use for loop to extract move names
const moveNames = [];
for (let i = 0; i < data.moves.length; i++) {
moveNames.push(data.moves[i].move.name);
}
setMoveList(moveNames);
}
fetchPokemon();
}, []);
if (moveList.length === 0) {
return <div>Loading...</div>;
}
return (
<div>
<h3>Moves:</h3>
<ul>
{moveList.map((move) => (
<li key={move}>{move}</li>
))}
</ul>
</div>
);
}
data.moves array using a for loopdata.moves[i].move.namemoveNames.push(data.moves[i].move.name).map() method: Transform array items into JSX elements for displaymoveList.map((move) => <li key={move}>...</li>).map() method is the built-in JavaScript way to do the map patternkey={move} (the move name itself).map()?.map() in JSX: Ideal for rendering because itâs clean, readable, and React-optimized. This is the popular shorthand youâll see in most React code.Note: Learn more about the built-in .map() method at MDN: Array.map()
Try mapping other pokemon data:
pokemon.types[i].type.namepokemon.abilities[i].ability.name