4

I am calling a get API in useEffect hook, to get the data before component mounts, but it's calling the API to many time and I am getting an error "To many API calls".

const [total, setTotal] = useState(0);
const [message, setMessage] = useState('');

useEffect(() => {
    covidApi.getData({url:'/totals'})
    .then((response) => {
        setTotal(response.data[0]);
        setMessage('');
        console.log(response.data);
    })
    .catch((error) => {
        setMessage("No data found");
        console.log(error);
    })
});

Output:

Browser Output

Please let me know is it the best way to get data from API before your component renders using useEffect hook.

Yousaf
  • 27,861
  • 6
  • 44
  • 69
MDMH
  • 83
  • 1
  • 8
  • 2
    Put **empty array** as effect's dependency: `useEffect(() => { ... }, [])`. Now this effect will run only once when component is **mounted**. – Ajeet Shah Apr 17 '21 at 13:58
  • dependency array is not defined, [] :( also if the dependency changes too frequently, You may want to look at `debouncing` or `throttling` mechanisms – keysl Apr 17 '21 at 13:59
  • 1
    Thanks a lot @AjeetShah it worked. can you please share some article on it(how to use useEffect as different life cycle method) if u have – MDMH Apr 17 '21 at 14:02
  • See [How to call loading function with React useEffect only once](https://stackoverflow.com/a/53121021/2873538) – Ajeet Shah Apr 17 '21 at 14:19
  • 1
    duplicate of - https://stackoverflow.com/questions/59606096/useeffect-re-renders-too-many-times#59606300 – Lakshman Kambam Apr 17 '21 at 14:20
  • 1
    See this article that explains all the use case of useEffect https://dmitripavlutin.com/react-useeffect-explanation/ – mohcine nazrhan Apr 17 '21 at 14:22
  • [React Docs - Using the Effect Hook](https://reactjs.org/docs/hooks-effect.html) – Yousaf Apr 17 '21 at 14:28
  • if you want call only once https://stackoverflow.com/a/65150997/10039122 – Yasin Tazeoglu Apr 17 '21 at 15:04

1 Answers1

5

Put a [] after the function in useEffect like this:

useEffect(() => {
    covidApi.getData({url:'/totals'})
    .then((response) => {
        setTotal(response.data[0]);
        setMessage('');
        console.log(response.data);
    })
    .catch((error) => {
        setMessage("No data found");
        console.log(error);
    })
}, []);

This will call the API only once.

Aqeel
  • 804
  • 1
  • 11
  • 15