I have a function handleScroll that is listened on the scroll event. Thsi function must update isFetching (that starts false and must change the boolean value).
The function handleScroll is correctly listened, as the console.log shows. However, isFetching is always false.
It seems like setIsFetching is never read. Another option, I think, is like the eventListener freezes the first version of the handleScroll function.
How can I do in order to update the hook in that function? Here is a simplified version of the code and the codesandbox :
/* <div id='root'></div> */
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
const debounce = (func, wait, immediate) => {
let timeout;
return function() {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(() => {
timeout = null;
if (!immediate) func.apply(context, args);
}, wait);
if (immediate && !timeout) func.apply(context, args);
};
};
const App = () => {
const [isFetching, setIsFetching] = useState(false);
const handleScroll = debounce(() => {
setIsFetching(!isFetching);
console.log({ isFetching });
}, 300);
useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, []);
return <div style={{ height: "1280px" }}>Hello world</div>;
};
const root = document.getElementById("root");
if (root) ReactDOM.render(<App />, root);
UPDATE
I put an empty array as a second param in the useEffect because I want that the first param function only fires once on componentDidMount()