Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using UseEffect Hook to Fetch API

I am trying to fetch cryptocurrency data from an api, by updating my state with the information pulled up. But when I do, my console.log is showing an empty object. And there is no data being passed down to my child components either. Did I do something wrong here?

import React, {useState, useEffect} from 'react';
import SmallBox from './SmallBox';
import './App.css';

function App() {
  const [smallData, setSmallData] = useState({})

  async function getAPI(){
    await fetch(`https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false
    `)
    .then(response => response.json())
    .then(data => setSmallData({data})); 
  }

  useEffect( () => {
    getAPI();
    console.log(smallData)
  }, []);


  return (
    <div className="app">
      
      {/* SmallBox - balance */}
      <SmallBox className="balance"/>
      
      {/* SmallBox - bitcoin */}
      <SmallBox className="bitcoin" coin={smallData}/>
      
      {/* SmallBox - ethereum */}
      <SmallBox className="ethereum" coin={smallData}/>
      
      {/* SmallBox - ripple */}
      <SmallBox className="ripple" coin={smallData}/>
      
      {/* SmallBox - tether */}
      <SmallBox className="tether" coin={smallData}/>
     
    </div>
  );
}

export default App;
like image 246
Owen Osagiede Avatar asked Oct 24 '25 01:10

Owen Osagiede


1 Answers

Try awaiting for the data to be fetched before logging it, instead of await for the fetch inside the async function getAPI:

  function getAPI(){
    return fetch(`https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false
    `)
      .then(response => response.json())
      .then(data => setSmallData({data})); 
  }

  useEffect( () => {
    getAPI()
      .then(() => console.log(smallData));
  }, []); // <- Add dependencies here

Note: I think getAPI is going to be called on every render of the component, which I don't think it's what you want. I suggest to add some dependency to the second variable (an empty array) passed to the useEffect function, telling React to call this effect only when that/those variables have changed. For example, you can add the currency.

like image 94
emi Avatar answered Oct 27 '25 01:10

emi