I need every 5 seconds (actually every 2 minutes, but having 5 seconds while testing) to make a GET request to an API. This should be done only when the user is logged in. The data should be displayed by one component that is called "Header". My first thought was to have an interval inside that component. So with "useEffect" I had this in the Header.js:
const [data, setData] = useState([]);
useEffect(async () => {
const interval = setInterval(async () => {
if(localStorage.getItem("loggedInUser")){
console.log("Logged in user:");
console.log(new Date());
try{
const data = await getData();
if(data){
setData(data);
}
console.log("data",data);
}
catch(err){
console.log("err",err);
}
}
}, 5000);
return () => clearInterval(interval);
}, []);
Im getting the data. But looking at the console, it does not look so good. First of all, sometimes I get this:
Warning: Can't perform a React state update on an unmounted component. This is a no-op,
but it indicates a memory leak in your application. To fix, cancel all subscriptions
and asynchronous tasks in a useEffect cleanup function.
It seems to happen when I go to other pages that have been called with a "href" (so without using for example history to change page). Also, probably because of the thing above, after a while that I browse the pages, I see that the interval is not every 5 seconds anymore. It happens 2-3 times every 5 seconds. Maybe every seconds. To me this does not look good at all. Im wondering first of all if this component is the right place to put the interval in. Maybe the interval should be in App.js? But then I would need a mechanism to pass data to children component (the Header.js, maybe could do this with Context).