I’m facing a bug not able to recognise where doing wrong, during my first loading pagNum = 0 is calling twice which is causing first 3 result repeating twice after that when scroll down pageNum= 1, pageNum = 2 all working perfectly.
I used python for my backend and mongo DB.
This is my code
import './App.css';
import { debounce } from 'lodash';
const App = () => {
const [videos, setVideos] = useState([]);
const [page, setPage] = useState(0);
const [loading, setLoading] = useState(false);
const [hasMore, setHasMore] = useState(true);
const limit = 3;
const [initialLoad, setInitialLoad] = useState(true); // New state to track initial load
useEffect(() => {
if (initialLoad) {
fetchVideos(page); // Initial load with page 0
setInitialLoad(false); // Set initialLoad to false after initial fetch
}
}, [page, initialLoad]); // Include page and initialLoad in dependency array
const fetchVideos = async (pageNum) => {
setLoading(true);
try {
const response = await fetch(`http://127.0.0.1:5000/videos?page=${pageNum}&limit=${limit}`);
const data = await response.json();
console.log('Fetched videos:', data);
if (data.length > 0) {
setVideos(prevVideos => [...prevVideos, ...data]);
setPage(pageNum + 1);
} else {
setHasMore(false);
}
} catch (error) {
console.error('Error fetching videos:', error);
} finally {
setLoading(false);
}
};
const handleScroll = useCallback(() => {
if (loading || !hasMore) return;
const lastVideo = document.querySelector('.video-list > .video-card:last-child');
if (!lastVideo) return;
const lastVideoOffset = lastVideo.offsetTop + lastVideo.clientHeight;
const pageOffset = window.pageYOffset + window.innerHeight;
const bottomOffset = 20;
if (pageOffset > lastVideoOffset - bottomOffset) {
fetchVideos(page);
}
}, [loading, hasMore, page]);
useEffect(() => {
const handleScrollDebounced = debounce(() => {
handleScroll();
}, 300);
window.addEventListener('scroll', handleScrollDebounced);
return () => window.removeEventListener('scroll', handleScrollDebounced);
}, [handleScroll]);
return (
<div className="App">
<h1>Music Reels</h1>
<div className="video-list">
{videos.map(video => (
<div className="video-card" key={video._id}>
<video controls autoPlay muted>
<source src={video.video_link} type="video/mp4" />
</video>
<div className="video-info">
<h2>{video.title}</h2>
<p>{video.description}</p>
<p>{new Date(video.uploaded_date).toLocaleDateString()}</p>
</div>
</div>
))}
{loading && <p>Loading...</p>}
{!loading && !hasMore && <p>No more videos</p>}
</div>
</div>
);
};
export default App;
If someone can help me in this. 🙂