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:

Please let me know is it the best way to get data from API before your component renders using useEffect hook.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With