DEV Community

Haruka Kakiuchi
Haruka Kakiuchi

Posted on

How to fetch API - React

Using Pokemon api
https://pokeapi.co/

How to get all data

import { useEffect } from 'react';
import { getAllPokemon } from './utils/pokemon'

function App() {
  const initialURL = `https://pokeapi.co/api/v2/pokemon/`;

  useEffect(() => {
    const fetchPokemonData = async function() {
      let res = await getAllPokemon(initialURL)
      console.log(res);
    }

    fetchPokemonData();
  }, [])


  return (
    <div className="App">

    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode
export const getAllPokemon = function (url) {
  return new Promise((resolve, reject) => {
    fetch(url)
      .then((res) => res.json())
      .then((data) => resolve(data));
  });
};

Enter fullscreen mode Exit fullscreen mode

Read each of data

const [pokemonData, setPokemonData] = useState([])

  useEffect(() => {
    const fetchPokemonData = async function() {
      let res = await getAllPokemon(initialURL)

      loadPokemon(res.results) // added
      setLoading(false)
    }


    fetchPokemonData();
  }, [])
Enter fullscreen mode Exit fullscreen mode
  const loadPokemon = async function(data) {
    let _pokemonData = await Promise.all(data.map((item) => {
      let pokemonRecord = getPokemon(item.url)
      return pokemonRecord;
    }))
    setPokemonData(_pokemonData)
  }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)