J
J
JekaHC2022-04-04 20:24:16
JavaScript
JekaHC, 2022-04-04 20:24:16

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 };


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 };


Pokemon.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 };


With fetch in main.jsx , I get twenty objects (Pokémon) with their unique name and a link to characteristics (each has its own):

624b2999dbc28909392330.png

If you follow any of these links (this is an API request), you will see a lot of characteristics of Pokemon:

624b29a8408ce467302127.png

From this data i need to get height, weight, sprite, type of each pokemon instead of links in index.html

Help me to do this...

API : https://pokeapi.co/

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2022-04-04
@JekaHC

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 question

Ask a Question

731 491 924 answers to any question