Concept: Reduce pattern with fetched data (using for loop)
Create a PokemonTotalWeight component that:
https://pokeapi.co/api/v2/pokemon?limit=20Displays:
Total Weight: 8500
Pokemon Count: 20
import { useState, useEffect } from 'react';
export default function PokemonTotalWeight() {
const [totalWeight, setTotalWeight] = useState(0);
const [count, setCount] = useState(0);
useEffect(() => {
async function fetchAndCalculateWeight() {
// Step 1: Fetch list of pokemon
const response = await fetch('https://pokeapi.co/api/v2/pokemon?limit=20');
const data = await response.json();
// Step 2: Fetch all pokemon details
const allPokemon = [];
for (let i = 0; i < data.results.length; i++) {
const pokemonResponse = await fetch(data.results[i].url);
const pokemon = await pokemonResponse.json();
allPokemon.push(pokemon);
}
// Step 3: REDUCE: Calculate total weight using for loop
let total = 0;
// Your reduce for loop here
setTotalWeight(total);
setCount(allPokemon.length);
}
fetchAndCalculateWeight();
}, []);
if (totalWeight === 0) {
return <div>Loading...</div>;
}
return (
<div>
{/* Display total weight and count */}
</div>
);
}
let total = 0allPokemon arraytotal = total + allPokemon[i].weighttotal += allPokemon[i].weightimport { useState, useEffect } from 'react';
export default function PokemonTotalWeight() {
const [totalWeight, setTotalWeight] = useState(0);
const [count, setCount] = useState(0);
useEffect(() => {
async function fetchAndCalculateWeight() {
// Step 1: Fetch list of pokemon
const response = await fetch('https://pokeapi.co/api/v2/pokemon?limit=20');
const data = await response.json();
// Step 2: Fetch all pokemon details
const allPokemon = [];
for (let i = 0; i < data.results.length; i++) {
const pokemonResponse = await fetch(data.results[i].url);
const pokemon = await pokemonResponse.json();
allPokemon.push(pokemon);
}
// Step 3: REDUCE: Calculate total weight using for loop
let total = 0;
for (let i = 0; i < allPokemon.length; i++) {
total = total + allPokemon[i].weight;
}
setTotalWeight(total);
setCount(allPokemon.length);
}
fetchAndCalculateWeight();
}, []);
if (totalWeight === 0) {
return <div>Loading...</div>;
}
return (
<div>
<p>Total Weight: {totalWeight}</p>
<p>Pokemon Count: {count}</p>
</div>
);
}
let total = 0total += allPokemon[i].weight.reduce() method does this automaticallyNote: Learn more about the built-in .reduce() method at MDN: Array.reduce()
?limit=20 to fetch only 20 pokemon at a timelimit: Number of items per page (we use 20)offset: Starting position for the next page (e.g., ?limit=20&offset=20 for page 2)Note: To fetch more pokemon, you could modify the limit or implement pagination to fetch multiple pages sequentially
Try calculating:
total / allPokemon.length