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.

8
  • 2
    Put empty array as effect's dependency: useEffect(() => { ... }, []). Now this effect will run only once when component is mounted. Commented Apr 17, 2021 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 Commented Apr 17, 2021 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 Commented Apr 17, 2021 at 14:02
  • 1
    duplicate of - stackoverflow.com/questions/59606096/… Commented Apr 17, 2021 at 14:20
  • 1
    See this article that explains all the use case of useEffect dmitripavlutin.com/react-useeffect-explanation Commented Apr 17, 2021 at 14:22

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.