Concept: Promises with fetch API and data transformation
Create a PokemonDisplay component that:
useState to store a simplified pokemon objectuseEffect to fetch a pokemon when the component loadshttps://pokeapi.co/api/v2/pokemon/pikachu{ name, height, weight, imgUrl }.then() chainWhen the component loads, it should fetch and display:
Name: pikachu
Weight: 60
Height: 4
[Image of pikachu]
import { useState, useEffect } from 'react';
// Define callback function outside the component
function transformPokemon(pokemonData) {
// Transform pokemonData to { name, height, weight, imgUrl }
// Find the first image URL (usually in pokemonData.sprites.front_default)
}
export default function PokemonDisplay() {
const [pokemon, setPokemon] = useState(null);
useEffect(() => {
// Fetch pokemon data here
}, []);
if (!pokemon) {
return <div>Loading...</div>;
}
return (
<div>
{/* Display name, weight, height, and image */}
</div>
);
}
fetch() with the API URL - it returns a Promise.then() to handle the responseresponse.json() to parse JSON - it also returns a PromisetransformPokemon function outside the component{ name, height, weight, imgUrl }pokemonData.sprites.front_default.then(transformPokemon) to transform the data.then(setPokemon) to store the transformed data.catch() to handle errorsimport { useState, useEffect } from 'react';
// Callback function defined outside the component
function transformPokemon(pokemonData) {
return {
name: pokemonData.name,
height: pokemonData.height,
weight: pokemonData.weight,
imgUrl: pokemonData.sprites.front_default
};
}
export default function PokemonDisplay() {
const [pokemon, setPokemon] = useState(null);
useEffect(() => {
fetch('https://pokeapi.co/api/v2/pokemon/pikachu')
.then(response => response.json())
.then(transformPokemon) // Use the callback function
.then(pokemon => setPokemon(pokemon)) // Set the transformed data
.catch(error => console.error('Error fetching pokemon:', error));
}, []);
if (!pokemon) {
return <div>Loading...</div>;
}
return (
<div>
<p>Name: {pokemon.name}</p>
<p>Weight: {pokemon.weight}</p>
<p>Height: {pokemon.height}</p>
{pokemon.imgUrl && <img src={pokemon.imgUrl} alt={pokemon.name} />}
</div>
);
}
.then() and .catch()fetch() returns a Promise that resolves to a Response objectresponse.json() returns a Promise that resolves to parsed JSON data.then() calls to handle each step of the async operation.then() can be defined outside the component.catch() to handle errorsuseState to store fetched datauseEffect to fetch data when component loadsTry modifying your transformPokemon function to include or exclude different properties:
id: pokemonData.id - The Pokemon’s unique ID numbertypes: pokemonData.types.map(t => t.type.name) - Array of type names (e.g., ['electric'])abilities: pokemonData.abilities.map(a => a.ability.name) - Array of ability namesbaseExperience: pokemonData.base_experience - Base experience pointsstats: Transform pokemonData.stats into a simpler object with just stat names and valuesmoves: pokemonData.moves.map(m => m.move.name) - Array of move names (first 5-10)backSprite: pokemonData.sprites.back_default - Back-facing sprite imageshinySprite: pokemonData.sprites.front_shiny - Shiny variant imageheight or weight if you don’t need themname and imgUrl for a minimal card viewpokemonData.types[0]?.type.namepokemonData.name.charAt(0).toUpperCase() + pokemonData.name.slice(1)pokemonData.weight / 10pokemonData.height / 10pokemonData.sprites.front_default?.)map() with your transform function