Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React useEffect calls API too many time, How can I limit the API call to only once when my component renders?

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.

like image 646
MDMH Avatar asked Oct 31 '25 05:10

MDMH


1 Answers

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.

like image 124
Aqeel Avatar answered Nov 01 '25 19:11

Aqeel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!