The tea shop's reviews page loads 20 reviews at a time. Under the list sits an element that says "Loading more reviews", the sentinel: when it gets near the screen, the next page should load. Write infiniteScroll(list, sentinel, loadPage). loadPage(page) returns a promise of { items, hasMore }, where items are the reviews' texts, and pages are numbered from 1. Add each item to list as an <li> with the item as its text, in order.
Watch the sentinel with one IntersectionObserver whose rootMargin is "300px", so the next page starts loading while the sentinel is still up to 300 px below the screen. When the observer reports the sentinel intersecting and no page is loading, load the next page. Never load two pages at once: reports that come during a load are ignored. When a page arrives with hasMore false, add its items and stop observing for good.
The observer reports only changes. If a page is too short to push the sentinel out of view, the sentinel stays in view, no new report comes, and the list would stop growing. So after adding a page that has more after it, stop watching the sentinel and start again: observe() always gives a first report that says where the sentinel is now, after the new reviews are laid out, and if it's still in view, the next page loads. When loadPage rejects, add nothing and keep watching as before, without observing again: the same page is asked for the next time the sentinel comes into view, not straight away, so a failing server isn't asked again and again.
Return a function that stops it all: the observer disconnects, and a page that's still loading is ignored when it arrives. The JavaScript question Why use IntersectionObserver instead of a scroll listener to detect when an element becomes visible? (intersectionobserver-vs-scroll-listener) explains why this beats checking positions on every scroll.
const stop = infiniteScroll(document.getElementById("reviews"), document.getElementById("more"), async (page) => {
const response = await fetch("/api/reviews?page=" + page);
const { reviews, next } = await response.json();
return { items: reviews.map((review) => review.text), hasMore: next };
});
const io = useIntersection();
const sentinel = document.getElementById("more");
const loadPage = spy(() => new Promise(() => {}));
infiniteScroll(document.getElementById("reviews"), sentinel, loadPage);
await flush();
const observers = io.observers();
expect(observers).toHaveLength(1);
expect(observers[0].options.rootMargin).toBe("300px");
expect(observers[0].targets).toHaveLength(1);
expect(observers[0].targets[0]).toBe(sentinel);
expect(loadPage.callCount).toBe(0);
const io = useIntersection();
const list = document.getElementById("reviews");
const sentinel = document.getElementById("more");
const pending = [];
const loadPage = spy((page) => new Promise((resolve, reject) => pending.push({ page, resolve, reject })));
infiniteScroll(list, sentinel, loadPage);
await flush();
io.enter(sentinel);
expect(loadPage.calls.map((call) => call.args)).toEqual([[1]]);
pending[0].resolve({ items: ["Lovely green tea", "The mint is too strong for me"], hasMore: false });
await flush();
expect(Array.from(list.children, (item) => item.tagName + ": " + item.textContent)).toEqual(["LI: Lovely green tea", "LI: The mint is too strong for me"]);
const io = useIntersection();
const list = document.getElementById("reviews");
const sentinel = document.getElementById("more");
const pending = [];
const loadPage = spy((page) => new Promise((resolve, reject) => pending.push({ page, resolve, reject })));
infiniteScroll(list, sentinel, loadPage);
await flush();
io.enter(sentinel);
io.leave(sentinel);
io.enter(sentinel);
expect(loadPage.callCount).toBe(1);
io.leave(sentinel);
pending[0].resolve({ items: ["Smooth oolong"], hasMore: true });
await flush();
expect(loadPage.callCount).toBe(1);
io.enter(sentinel);
expect(loadPage.calls.map((call) => call.args[0])).toEqual([1, 2]);
const io = useIntersection();
const list = document.getElementById("reviews");
const sentinel = document.getElementById("more");
const pending = [];
const loadPage = spy((page) => new Promise((resolve, reject) => pending.push({ page, resolve, reject })));
infiniteScroll(list, sentinel, loadPage);
await flush();
io.enter(sentinel);
pending[0].resolve({ items: ["One"], hasMore: true });
await flush();
expect(loadPage.calls.map((call) => call.args[0])).toEqual([1, 2]);
pending[1].resolve({ items: ["Two"], hasMore: true });
await flush();
expect(loadPage.calls.map((call) => call.args[0])).toEqual([1, 2, 3]);
expect(list.textContent).toBe("OneTwo");
const io = useIntersection();
const list = document.getElementById("reviews");
const sentinel = document.getElementById("more");
const pending = [];
const loadPage = spy((page) => new Promise((resolve, reject) => pending.push({ page, resolve, reject })));
infiniteScroll(list, sentinel, loadPage);
await flush();
io.enter(sentinel);
pending[0].resolve({ items: ["The last review"], hasMore: false });
await flush();
expect(io.observers()[0].targets).toHaveLength(0);
io.leave(sentinel);
io.enter(sentinel);
await flush();
expect(loadPage.callCount).toBe(1);
expect(list.children).toHaveLength(1);
const io = useIntersection();
const list = document.getElementById("reviews");
const sentinel = document.getElementById("more");
const pending = [];
const loadPage = spy((page) => new Promise((resolve, reject) => pending.push({ page, resolve, reject })));
infiniteScroll(list, sentinel, loadPage);
await flush();
io.enter(sentinel);
pending[0].reject(new Error("The server is busy"));
await flush();
expect(list.children).toHaveLength(0);
expect(loadPage.callCount).toBe(1);
io.leave(sentinel);
io.enter(sentinel);
expect(loadPage.calls.map((call) => call.args[0])).toEqual([1, 1]);
pending[1].resolve({ items: ["Back again"], hasMore: false });
await flush();
expect(list.textContent).toBe("Back again");
const io = useIntersection();
const list = document.getElementById("reviews");
const sentinel = document.getElementById("more");
const pending = [];
const loadPage = spy((page) => new Promise((resolve, reject) => pending.push({ page, resolve, reject })));
const stop = infiniteScroll(list, sentinel, loadPage);
await flush();
io.enter(sentinel);
stop();
expect(io.observers()[0].disconnected).toBe(true);
pending[0].resolve({ items: ["Too late"], hasMore: true });
await flush();
expect(list.children).toHaveLength(0);
expect(loadPage.callCount).toBe(1);
const clock = useFakeTimers();
const io = useIntersection();
const list = document.getElementById("reviews");
const sentinel = document.getElementById("more");
const fetch = useFetch((url) => {
const page = Number(url.split("page=")[1]);
return { body: { reviews: ["Review " + page + "a", "Review " + page + "b"], next: page < 2 }, delay: 100 };
});
infiniteScroll(list, sentinel, async (page) => {
const response = await fetch("/api/reviews?page=" + page);
const data = await response.json();
return { items: data.reviews, hasMore: data.next };
});
await flush();
io.enter(sentinel);
for (let round = 0; round < 3; round++) await clock.runAllAsync();
expect(fetch.calls.map((call) => call.url)).toEqual(["/api/reviews?page=1", "/api/reviews?page=2"]);
expect(Array.from(list.children, (item) => item.textContent)).toEqual(["Review 1a", "Review 1b", "Review 2a", "Review 2b"]);
expect(io.observers()[0].targets).toHaveLength(0);
Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.
Ctrl + Enter runs the tests (⌘ + Enter on a Mac).
I'm here to help with Infinite scroll with a sentinel. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.