codex-lv3-may-2025

Kata 12: Fetch and Display Pokemon

Concept: Promises with fetch API and data transformation

Challenge

Create a PokemonDisplay component that:

  1. Uses useState to store a simplified pokemon object
  2. Uses useEffect to fetch a pokemon when the component loads
  3. Fetches from: https://pokeapi.co/api/v2/pokemon/pikachu
  4. Transforms the pokemon data to a simpler object: { name, height, weight, imgUrl }
  5. Uses a callback function defined outside the component in the .then() chain
  6. Displays the pokemon’s name, weight, height, and image

🔗 Practice on CodeSandbox

Expected Output

When the component loads, it should fetch and display:

Name: pikachu
Weight: 60
Height: 4
[Image of pikachu]

Starter Code

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>
  );
}

Hints

Solution

Click to reveal solution
import { 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>
  );
}

Concept Review

Variations & Extensions

Try modifying your transformPokemon function to include or exclude different properties:

Add More Properties

Simplify Further

Transform Data

Challenge Ideas


Back to Kata Index