codex-lv3-may-2025

Kata 13: Fetch and Display Pokemon (Async/Await)

Concept: Async/await with fetch API

Challenge

Create a PokemonDisplay component that:

  1. Uses useState to store a pokemon object
  2. Uses useEffect to fetch a pokemon when the component loads
  3. Fetches from: https://pokeapi.co/api/v2/pokemon/pikachu
  4. Displays the pokemon’s name, weight, and height

🔗 Practice on CodeSandbox

Expected Output

When the component loads, it should fetch and display:

Name: pikachu
Weight: 60
Height: 4

Starter Code

import { useState, useEffect } from 'react';

export default function PokemonDisplay() {
  const [pokemon, setPokemon] = useState(null);
  
  useEffect(() => {
    // Fetch pokemon using async/await
    // Store result in state
  }, []);
  
  if (!pokemon) {
    return <div>Loading...</div>;
  }
  
  return (
    <div>
      {/* Display name, weight, and height */}
    </div>
  );
}

Hints

Solution

Click to reveal solution
import { useState, useEffect } from 'react';

export default function PokemonDisplay() {
  const [pokemon, setPokemon] = useState(null);
  
  useEffect(() => {
    async function fetchPokemon() {
      const response = await fetch('https://pokeapi.co/api/v2/pokemon/pikachu');
      const data = await response.json();
      setPokemon(data);
    }
    
    fetchPokemon();
  }, []);
  
  if (!pokemon) {
    return <div>Loading...</div>;
  }
  
  return (
    <div>
      <p>Name: {pokemon.name}</p>
      <p>Weight: {pokemon.weight}</p>
      <p>Height: {pokemon.height}</p>
    </div>
  );
}

Concept Review

Why We Wrap Async Logic Inside useEffect

useEffect, cannot take an async function as a callback.

  useEffect(async () => { // Wrong!!
        const response = await fetch('https://pokeapi.co/api/v2/pokemon/pikachu');
        // ...
    }
  }

Why? useEffect expects its callback to return either nothing or a cleanup function—not a Promise. Declaring the effect callback as async would make it return a Promise implicitly, which React treats as a cleanup and warns about. The common pattern is to define an async helper inside the effect (or an immediately invoked async function) and call it right away, leaving the outer effect synchronous. See the React docs for more on what effect callbacks should return.


Back to Kata Index