user

Jo Micheal

7 Apr 2022

[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

7 Apr 2022

Best Answer

best answer
githubgithubgithub

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

Replies

Jo Micheal

7 Apr 2022

Thanks 

© 2024 Copyrights reserved for web-brackets.com