'How modify API request?
I have few React Components :
Main.jsx
import { useState, useEffect } from "react";
import { Preloader } from "../Preloader";
import { Pokemons } from "../Pokemons";
function Main() {
const [pokemons, setPokemons] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(function getPokemons() {
fetch("https://pokeapi.co/api/v2/pokemon?limit=20")
.then((responce) => responce.json())
.then((data) => {
data.results && setPokemons(data.results);
setLoading(false);
});
}, []);
return (
<main className="container content">
{loading ? <Preloader /> : <Pokemons pokemons={pokemons} />}
</main>
);
}
export { Main };
Pokemon.jsx
function Pokemon(props) {
const { name: name, url: url } = props;
return (
<ul className="collection with-header">
<li className="collection-header">
<h4>{name}</h4>
</li>
<li className="collection-item"></li>
<li className="collection-item">{url}</li>
</ul>
);
}
export { Pokemon };
Pokemons.jsx
import { Pokemon } from "./Pokemon";
function Pokemons(props) {
const { pokemons = [] } = props;
if (!pokemons.length) {
return <h4 className="pokemons_error">Nothing found</h4>;
}
return (
<div className="pokemons">
{pokemons.map((pokemon, id) => (
<Pokemon key={id} {...pokemon} />
))}
</div>
);
}
export { Pokemons };
Thanks to fetch in main.jsx, I get twenty objects (Pokémon) with their unique name and a link to the characteristics (each has its own):
If you go to any of these links (This is an Api request), you can see many characteristics of the Pokémon:
From this data, I need to get the height, weight, sprite,type of each pokemon instead of links in index.html
HOW? Help me...
API : https://pokeapi.co/
Solution 1:[1]
You need to modify your Pokemon.jsx like this:
function Pokemon(props) {
const { name, height, weight, sprites, types } = props;
const sprite = sprites.front_default; // you can select on of sprites
const type = types[0].type; // just taking the first type
return (
<ul className="collection with-header">
<li className="collection-header">
<h4>{name}</h4>
</li>
<li className="collection-item"></li>
<li className="collection-item">{height}</li>
<li className="collection-item">{weight}</li>
<li className="collection-item">
<img src={sprite} />
</li>
<li className="collection-item">{type}</li>
</ul>
);
}
export { Pokemon };
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Maxim Filippov |
