javascript - ReactAxios send infinite number of requests - Stack Overflow

admin2025-04-09  0

I'm fetching data from my backend api when ponent mount and can do it successfuly but my React app keeps sending requests to the server causing it to slow down. I used useEffect hook, but I'm getting the same result without using the hook.

useEffect(() => {
   axios.get('http://127.0.0.1:8000/food_category/')
  .then(response => {
   setFoodCategory(response.data);
   console.log(response.data);
})});

What am I doing wrong?

I'm fetching data from my backend api when ponent mount and can do it successfuly but my React app keeps sending requests to the server causing it to slow down. I used useEffect hook, but I'm getting the same result without using the hook.

useEffect(() => {
   axios.get('http://127.0.0.1:8000/food_category/')
  .then(response => {
   setFoodCategory(response.data);
   console.log(response.data);
})});

What am I doing wrong?

Share Improve this question asked Dec 12, 2019 at 9:05 Renato MaretićRenato Maretić 3551 gold badge7 silver badges21 bronze badges 1
  • 1 Each time you use setFoodCategory the ponent is mounted again and useEffect is executed. Try useEffect( () => { ... }, []). The empty array parameter at the end will execute useEffect only once. – devamat Commented Dec 12, 2019 at 9:16
Add a ment  | 

1 Answer 1

Reset to default 10

If you give no dependencies to the useEffect hook, it will execute every time your ponent renders (which will happen infinitely because you set the state after getting data and thus your ponent rerenders).

Check out the second argument of useEffect in the docs to learn more about it.

An empty dependencies array indicates the useEffect will act as a mount and only executes once.

useEffect(() => {
    // Do mount stuff here such as executing your request.
}, []);
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744128482a232573.html

最新回复(0)