Concept: Async/await with fetch API
Create a PokemonDisplay component that:
useState to store a pokemon objectuseEffect to fetch a pokemon when the component loadshttps://pokeapi.co/api/v2/pokemon/pikachuWhen the component loads, it should fetch and display:
Name: pikachu
Weight: 60
Height: 4
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>
);
}
async function inside useEffectfetch() with the API URLawait response.json() to parse JSONname, weight, height propertiessetPokemon() with the fetched dataimport { 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>
);
}
async function allows using await insideawait fetch() waits for the HTTP request to completeawait response.json() waits for JSON parsinguseState to store fetched datauseEffect to fetch data when component loadsuseEffectuseEffect, 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.