1
const [voltage1, getVoltage1] = useState(0)
const [voltage2, getVoltage2] = useState(0)
const [voltage3, getVoltage3] = useState(0)



useEffect(() => { 
    const abortCont = new AbortController();
    axios.get("http://localhost:8080/status", {mode: 'cors',signal: abortCont.signal, headers: { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
   }}).then((res) =>  {
        return res.data; 
    }).then((data) => {
      
        getVoltage1(data.data.status.voltageL1)
        getVoltage2(data.data.status.voltageL2)
        getVoltage3(data.data.status.voltageL3)

    } 
    ).catch(err => {
        console.log(err);
    })
    
    
});

I seem to be getting only 2 calls to my API even though I am using useEffect with no second argument. I don't understand why this is happening and how can I make it so the useEffect is being called infinitely.

  • Without the dependency array, the useEffect will run on every render, and since you're updating state in the useEffect it will likely loop forever – evolutionxbox Jul 19 '22 at 14:44
  • Does this answer your question? [Infinite loop in useEffect](https://stackoverflow.com/questions/53070970/infinite-loop-in-useeffect) – evolutionxbox Jul 19 '22 at 14:44
  • No I actually want the useEffect to keep making infinite calls to my API, I understand that by adding an empty array it makes it run once but I didn’t add that so why isn’t running infinitely – user19580437 Jul 20 '22 at 15:19

1 Answers1

0

I was able to fix this issue, the API was so fast that the values for voltage didn't update, thus the useState did not change and so the component never re-renders. My solution was to just add another state variable counter that increments every time UseEffect is called. Now useEffect is being called constantly.

 const [count, setCount] = useState(0)
const [voltage1, getVoltage1] = useState(0)
const [voltage2, getVoltage2] = useState(0)
const [voltage3, getVoltage3] = useState(0)

useEffect(() => { 
    const abortCont = new AbortController();
    axios.get("http://localhost:8080/status", {mode: 'cors',signal: abortCont.signal, headers: { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8'
   }}).then((res) =>  {
      
        return res.data; 

    }).then((data) => {
        setCount(count + 1)
        getVoltage1(data.data.voltageL1)
        getVoltage2(data.data.voltageL2)
        getVoltage3(data.data.voltageL3)
        console.log(data.data)
        
    }
    ).catch(err => {
        console.log(err);
    })
    
    
});