user image

Jo Micheal
Published in : 2022-04-07

[solved] useEffect is repeating the request Reactjs

React js

I am using useEffect in my functional component but this method is repeating the request a lot of times until the server response with 429 too many requests, here is the code I am using 

  const getData = useCallback(async () => {
    try{
      let res = await axios.get(BackendURL+'/user/accounts/all');
      setAccounts(res.data);
    }catch(err){  
      console.error(err);
    }
  });

  useEffect(() => {
    getData(); 
  }, [getData]);

Any idea How can I fix it?

Comments

Mohamed Atef Date : 2022-04-07

Best answers

46

Best answers

46

That's because your useCallback function is missing the independence array you need to add [ ] as a second parameter inside the useCallback function so your code should looks like 

  const getData = useCallback(async () => {
    try{
      let res = await axios.get(BackendURL+'/user/accounts/all');
      setAccounts(res.data);
    }catch(err){  
      console.error(err);
    }
    //Note in the line below 
  }, [ ]);

  useEffect(() => {
    getData(); 
  }, [getData]);

Good luck

Jo Micheal Date : 2022-04-07

Thanks 

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

How to get the selected object in "Autocomplete material ui"?
Publish date: 2021-12-22 | Comments: 2

Tag: React js

[solved] Expected a conditional expression and instead saw an assignment
Publish date: 2021-11-29 | Comments: 0

Tag: React js

React Component displaying a list of lines
Publish date: 2022-03-19 | Comments: 3

Tag: React js

Warning: React.jsx: type is invalid
Publish date: 2022-05-06 | Comments: 1

Tag: React js

Unexpected mix of '&&' and '||' Reactjs
Publish date: 2021-10-30 | Comments: 0

Tag: React js

TypeError: Super expression must either be null or a function
Publish date: 2022-03-13 | Comments: 2

Tag: React js

Best way to update the state in one class component from the redux store?
Publish date: 2022-03-30 | Comments: 3

Tag: React js

useStyles Invalid hook call class component
Publish date: 2022-02-10 | Comments: 2

Tag: React js