0

I am trying to fetch Data from an Api. I am getting the required result but when I try to console log it , it is console logging 4 times.

This is my app.js where I am using the fetchData.


import React, {useEffect, useState} from 'react';
import styles from './App.modules.css';
import {Header, Cards, Footer, Map, Table, Statecards} from './components/exports';
import {fetchData} from './api';

function App() {

  const [data, setData] = useState({});

  useEffect(() => {
     const settingData =  async () => {
      const data = await fetchData();
      setData(data);
    }     
    settingData();
    }, []);

 console.log(data); 


  return <div className = {styles.container}>
         <Header />
         </div>

  ;
}

export default App;

This is the fetchData function

import axios from 'axios';

const url = 'https://api.covid19india.org/data.json';

export const fetchData = async () => {
try{
    const response = await axios.get(url);
    return response;
}
catch(err){ 
    console.log(err);
}   
};

The console.log in the app.js is giving 4 console logs as below

enter image description here

I am not being able to figure out what's wrong.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
atul-gairola
  • 139
  • 1
  • 2
  • 6
  • Possible Duplicate of [Why does useState cause the component to render twice on each update?](https://stackoverflow.com/questions/61578158/why-does-usestate-cause-the-component-to-render-twice-on-each-update/61578206#61578206) – Shubham Khatri Jun 02 '20 at 03:57

1 Answers1

-1
  const settingData = async () => {
      const data = await fetchData();
      setData(data);
  }     
  useEffect(() => {
    settingData();
  }, []);

try this one.

kyun
  • 9,710
  • 9
  • 31
  • 66
  • I think you are missing a depedency in your useEffect. ```settingData``` should be added as a depedency or move the function inside ```useEffect``` like OP did in the question. – Junius L Jun 02 '20 at 04:24