I have this component in my app where i am trying to implement infinite scroll according to this tutorial.
export const MainJobs = () => {
const [items, setItems] = useState([]);
const [ind, setInd] = useState(1);
const errText = useLang(
"sagas // Something went wrond // fasa"
);
const [element, setElement] = useState(null);
const incrementState = () => {
console.log(ind, ind + 1); //logs 1,2
setInd(ind + 1);
};
useEffect(() => {
const fetchInfo = async () => {
const res = await fetch(`/api/search/vacancy?page=${ind}`);
if (res.ok) {
const data = await res.json();
setItems(data);
} else {
pop({
icon: "error",
title: "Oops...",
text: errText
});
}
};
fetchInfo();
}, [ind]);
useEffect(() => {
const currentElement = element;
const currentObservor = observor.current;
if (currentElement) {
currentObservor.observe(currentElement);
}
return () => {
if (currentElement) {
currentObservor.unobserve(currentElement);
}
};
}, [element]);
const observor = useRef(
new IntersectionObserver(
entries => {
const first = entries[0];
if (first.isIntersecting) {
incrementState();
}
},
{ threshold: 1 }
)
);
return (
<div className="mainjobs-container">
...rest of markup
<div className="bottom" ref={setElement}></div>
</div>
);
};
It logs 1,2 every time but doesn't increment ind. Also in devtools ing increments to 2 and then stops.
I need to increment ind every time incrementState function is called.
P.S i think the problem is about useRef or in Observor.