Home > Software design >  React fetch api keep requesting on loop
React fetch api keep requesting on loop

Time:04-14

function getCharacter(){
    fetch("http://localhost:8001/tinder-card").then((resp)=>resp.json()).then((result)=>{
        if(result.status==false){
            alert("No card found in database")
        }
        else{
            setpeople(result)
        }
        
    })
}


useEffect(()=>{
    getCharacter();
})

This is my react code where I am fetching user data from the node API everything is working fine but when i see my browser network tab fetch api is keep requesting on a loop and this is making my computer freeze how can i solve this?

CodePudding user response:

Add an empty array as the second argument of useEffect().

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

Otherwise useEffect will run every time your component re-renders causing this infinite loop.

CodePudding user response:

you might need to pass deps as [].

React.useEffect(() => {
     fetch("http://localhost:8001/tindercard").then((resp)=>resp.json()).then((result)=>{
               if(result.status==false){
                   alert("No card found in database")
               }
               else{
                   setpeople(result)
               }
               
           })
    }, []);

CodePudding user response:

You can pass an empty array as a second argument for useEffect, maybe your question is duplicated here

useEffect(()=>{
getCharacter();
},[])
  • Related