Advertisement
fakesamgregory

Master React in Webflow - Getting Data

Nov 11th, 2024 (edited)
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { useEffect, useState } from "react";
  2.  
  3. const getEvolutionChain = (chain) => {
  4.   const evolutionChain = [];
  5.  
  6.   const getNextChain = (pokemon) => {
  7.     evolutionChain.push(pokemon.species.name);
  8.  
  9.     if (pokemon.evolves_to.length) {
  10.       getNextChain(pokemon.evolves_to[0]);
  11.     }
  12.   };
  13.  
  14.   getNextChain(chain);
  15.  
  16.   return evolutionChain;
  17. };
  18.  
  19. export default function List() {
  20.   const [pokemon, setPokemon] = useState([]);
  21.   const [isLoading, setIsLoading] = useState(false);
  22.   const [isError, setIsError] = useState(false);
  23.  
  24.   useEffect(async () => {
  25.     const url = "https://pokeapi.co/api/v2/evolution-chain/1/";
  26.  
  27.     try {
  28.       setIsLoading(true);
  29.       const repsonse = await fetch(url);
  30.       const pokemonData = await repsonse.json();
  31.       const evolutionChain = getEvolutionChain(pokemonData.chain);
  32.       setPokemon(evolutionChain);
  33.     } catch (e) {
  34.       console.log(e);
  35.       setIsError(e.message);
  36.     } finally {
  37.       setIsLoading(false);
  38.     }
  39.   }, [setIsError, setIsLoading, setPokemon]);
  40.  
  41.   return isError ? (
  42.     <>{isError}</>
  43.   ) : isLoading ? (
  44.     <>Loading...</>
  45.   ) : (
  46.     <ul>
  47.       {pokemon.map((text) => (
  48.         <li>{text}</li>
  49.       ))}
  50.     </ul>
  51.   );
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement