Reputation: 31
I am making a news app and I have implemented infinite scroll using React Query. But my cocern was as more and more dom elements get added to the dom because of infinite scroll the dom gets heavy . To solve this I wanted to implement List virtualization using React-window . But I am not able to do so. My code -
async function fetchPage({ pageParam = 1 }) {
const response = await fetch(
`https://newsapi.org/v2/everything?q=India&pageSize=30&page=${pageParam}&apiKey=${API_KEY}`
);
return response.json();
}
function App() {
const { isLoading, data, fetchNextPage, isFetchingNextPage, hasNextPage } =
useInfiniteQuery(["news"], fetchPage, {
getNextPageParam: (lastpage, allpages) => {
const nextPage = allpages.length + 1;
return lastpage.articles.length !== 0 ? nextPage : undefined;
},
});
const observedElement = useRef(null);
useEffect(() => {
console.log("I am loading");
if (isLoading) return;
console.log("I am running");
const callback = (entries) => {
if (entries[0].isIntersecting && hasNextPage) {
fetchNextPage();
}
};
const option = { threshold: 0 };
const observer = new IntersectionObserver(callback, option);
const element = observedElement.current;
observer.observe(element);
return () => observer.unobserve(element);
}, [hasNextPage, fetchNextPage, isLoading]);
if (isLoading) {
return <p>Loading ...</p>;
}
const news = data.pages;
console.log(news);
return (
<>
<div className="app">
{news.map((n) =>
n.articles.map((a) => (
<article key={a.title} className="news_article">
<section>
<img src={a.urlToImage}></img>
</section>
<h2>
<a href={a.url}>{a.title}</a>
</h2>
<p>{a.description}</p>
<p>{a.author}</p>
</article>
))
)}
<div className="loader" ref={observedElement}>
{isFetchingNextPage && hasNextPage ? "Loading..." : "No search left"}
</div>
</div>
</>
);
}
export default App
The structure of the data is -
{
"status": "ok",
"totalResults": 9592,
-"articles": [
-// The news articles
},
Upvotes: 1
Views: 328