I'm using next js for my web application. I want to write function that will update the scroll position using useState
. For some reason, the useState isn't updating itself properly as I also need to calculate the maximum value from the function. Here is my code:
const [lazyProgress,setLazyProgress] = useState(0);
const [lazyProgressMax,setLazyProgressMax] = useState(0);
function lazyProgressUpdate(){
const scrollTotal = document.documentElement.scrollTop;
const heightWin = document.documentElement.scrollHeight - document.documentElement.clientHeight;
const scroll = scrollTotal / heightWin * 100;
setLazyProgress(scroll);
if(lazyProgress > lazyProgressMax){
setLazyProgressMax(lazyProgress);
}
console.log(lazyProgress,lazyProgressMax)
}
useEffect(()=>{
const timer = setInterval(()=>{
lazyProgressUpdate();
},8000);
return ()=>{
clearInterval(timer);
}
},[]);
In the above snippet, lazyProgress and lazyProgressMax are always 0 in the function. So neither of them get updated.
How do i overcome this issue