I am implementing the infinite scrolling in reactjs using the intersectionobserver API. Its a social-media website where i need to fetch comment for each post. Initially the showAmount is set to 15, and after each time the observer found the reference (last item), it increases the showAmount by 5 and re-render the new items. The problem with my code is, it works fine for the first time where the observer detects the item and fetch new comment and re-render. But after the re-rendering, the ref still pointing to the same item (15th item) where it should be now pointing to the latest last item (20th item).
Code:
// Callback function for the Intersection Observer
const handleIntersection = (entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log("intersect");
setShowAmount(showAmount+5);
}
});
};
useEffect(() => {
console.log("Updated showAmount:", showAmount);
retrieveComments();
}, [showAmount]);
useEffect(() => {
// Initialize the Intersection Observer only when the modal is open
if (isModalOpen) {
const observer = new IntersectionObserver(handleIntersection, {
root: null,
rootMargin: '0px',
threshold: 0.5
});
if (targetRef.current) {
observer.observe(targetRef.current);
}
// Cleanup function
return () => {
if (targetRef.current) {
observer.unobserve(targetRef.current);
}
};
}
}, [isModalOpen, targetRef]);
Rendering:
{/* Comment body */}
<div className="card" style={{borderRadius: '0px', border: 'None'}}>
<div className="card-body row" style={{}}>
<div className="col-md-12">
<div className="row" style={{paddingLeft: '15px', paddingRight: '10px'}}>
<div className="col-md-12">
{commentContents ?
commentContents.commentModal.length > 0 ? (
commentContents.commentModal.slice(0, showAmount).map((comments, outerIndex) => {
return (
<div ref={parseInt(outerIndex) === showAmount - 1 ? targetRef : null}>
{/* Outer comment section */}
<div className="d-flex align-items-center" style={{marginBottom: '12px'}}
key={'-' +comments.outerComment[1]+ '-' +comments.outerComment[3]+ '-' +outerIndex}>
.....more rendering