Answer the question
In order to leave comments, you need to log in
How to modify my API request?
I have multiple 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 };
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 };
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 };
Answer the question
In order to leave comments, you need to log in
function Pokemon({ name, url }) {
const [ data, setData ] = useState(null);
useEffect(() => {
fetch(url).then(r => r.json()).then(setData);
}, [ url ]);
return (
<div>
<h4>{name}</h4>
{data
? <div>
<ul>{data.abilities.map(n => <li>{n.ability.name}</li>)}</ul>
<img src={data.sprites.front_default} />
</div>
: <div>loading...</div>
}
</div>
);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question