SolidJSS
SolidJS11mo ago
17 replies
Luka

Infinite scroll

I want to make infinite scrolling on notifications page since this is notifications page I don't use SSR, What I have problems with is how observer sees the last element of array. When I have elements enough to show scrollbar it doesn't have problems since it doesn't intersect with last element so my fetch request doesn't run twice but if I have small amounts of elements it sees the last element so it makes another request

here is the code:
createEffect(() => { if (observer) { observer.disconnect(); } const options = { root: document.querySelector("#notificationsArea"), rootMargin: "0px", threshold: 1.0, }; const callback = (entries) => { entries.forEach((entry) => { if (entry.isIntersecting) { fetchData(); if (observer) { observer.unobserve(entry.target); } } }); }; observer = new IntersectionObserver(callback, options); if (notifications().length) { const newLastNotification = notifications()[notifications().length - 1]; if (lastNotification && newLastNotification.id !== lastNotification.id) { lastNotification.id = newLastNotification.id; lastNotification.created_at = newLastNotification.created_at; const target = document.querySelector(#${CSS.escape(lastNotification.id)}); if (target) { observer.observe(target); } } } else { fetchData() } });

fetchData is an async function that makes request to api and runs setNotifications(prev => [...prev, ...newData])

I thought of counting all the rows in postgresql so then I would probably check if the last element should be observed or not by observer API so it won't no longer make 2 requests.
Was this page helpful?