i've implemented infinite scroll hook for my newspage
const [posts, setPosts] = useState([]);
const [currentOffset, setCurrentOffset] = useState(0);
const [isLoading, setLoading] = useState(true);
const [isFetching, setIsFetching] = useState(false);
let loadThreePosts = () => {
axios.get(`/news?limit=3&offset=${currentOffset}`).then(({ data }) => {
let threePosts = [];
console.log(data);
data.data.forEach((p) => threePosts.push(p));
setPosts((posts) => [...posts, ...threePosts]);
setLoading(false);
});
setCurrentOffset(currentOffset 3);
};
useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => window.removeEventListener("scroll", handleScroll);
}, []);
useEffect(() => {
if (!isFetching) return;
fetchMorePosts();
}, [isFetching]);
function handleScroll() {
if (
window.innerHeight document.documentElement.scrollTop !==
document.documentElement.offsetHeight ||
isFetching
)
return;
setIsFetching(true);
}
function fetchMorePosts() {
setTimeout(() => {
loadThreePosts();
setIsFetching(false);
}, 2000);
}
So if i go to the newspage throw the Link on my site it fetching posts as i need, but if i paste newspage link in browser address bar it's not fetch anything
CodePudding user response:
Change your code to this:
useEffect(() => {
window.addEventListener("scroll", handleScroll);
handleScroll(); // Call handleScroll function
return () => window.removeEventListener("scroll", handleScroll);
}, []);