In a SwiftUI timeline built with a LazyVStack, how do you load older posts as the user nears the bottom without duplicate loads?
answer
- rows exist only when needed
- the last row's appearance
- guard in-flight and end-of-feed
- append, never replace the array
basics
~20 sTrigger the load from a row the LazyVStack creates only near the end, usually the last post's onAppear, and make the model's load idempotent with isLoading and hasMore guards. Append each page so existing rows keep their identity.
solid answer
~50 sBecause a `LazyVStack` builds rows only as they approach the viewport, the last row's `onAppear` runs when the reader nears the end, which makes it the natural trigger. Check that the appearing post is the last one (or within a few of it, to prefetch earlier), then call the model. The model guards against duplicates: it returns early while `isLoading` is true or once `hasMore` is false, and it appends the next page so existing rows keep their identity. A short page re-arms itself, because the new last row appears on screen at once. Two traps: in a plain `VStack` the last row is created at load, so the trigger fires immediately and keeps firing; and a spinner placed after the `ForEach` that stays on screen will not call `onAppear` again. On iOS 18, `onScrollVisibilityChange(threshold:_:)` offers a visibility-based trigger.
code
swift · 46 linesimport SwiftUI
struct Post: Identifiable, Sendable {
let id: Int
let text: String
}
@MainActor @Observable
final class TimelineModel {
private(set) var posts: [Post] = []
private(set) var isLoading = false
private(set) var hasMore = true
func loadOlder() async {
guard !isLoading, hasMore else { return }
isLoading = true
defer { isLoading = false }
let page = await fetchPage(olderThan: posts.last?.id)
posts.append(contentsOf: page)
hasMore = !page.isEmpty
}
private func fetchPage(olderThan id: Int?) async -> [Post] { [] }
}
struct TimelineView: View {
@State private var model = TimelineModel()
var body: some View {
ScrollView {
LazyVStack(alignment: .leading) {
ForEach(model.posts) { post in
Text(post.text)
.onAppear {
guard post.id == model.posts.last?.id else { return }
Task { await model.loadOlder() }
}
}
if model.isLoading {
ProgressView()
}
}
}
.task { await model.loadOlder() }
}
}go deeper
Remember that a LazyVStack creates rows only near the screen, so the last row appearing means the reader is near the end of the loaded posts.
Walk through the trigger, the isLoading and hasMore guards, appending pages, and why the same pattern in a VStack loads every page at once.
Diagnose stalls and double loads: a spinner trigger that never reappears, ids that change between pages, and a missing in-flight guard in the model.
Decide where pagination logic lives so every feed shares one idempotent loader, and when an iOS 18 deployment target justifies visibility-based triggers.
## Why the lazy stack is the trigger An infinite timeline needs one signal: **the reader is close to the end of what we have**. In SwiftUI, a `LazyVStack` inside a `ScrollView` provides it for free, because it **creates a row only when that row is about to be rendered**. A row's `onAppear` action runs before the row's first frame, so for the last post in the array it runs when the reader scrolls near the bottom, and not before. This is precisely what an eager `VStack` breaks. A `VStack` creates all of its children when it is displayed, so the last row "appears" at load. The trigger fires, a page is appended, the new last row is also created at once, and the screen can pull page after page with nobody scrolling. ## The pattern, step by step 1. **Initial page.** Start the first load from the screen, for example with `task` on the `ScrollView`. 2. **Near-end trigger.** On each row, `onAppear` checks whether this post is the last one (`post.id == posts.last?.id`). To prefetch earlier, check whether the post is among the last few instead. 3. **Idempotent load.** The model owns the guards; the view only asks. 4. **Append.** Add the page to the end of the array. Existing rows keep their identity and their scroll position. 5. **Progress row.** Show a `ProgressView` after the `ForEach` while `isLoading` is true. The model guards are what prevent duplicates: - **`isLoading`**: a second trigger during an in-flight request returns at once. Without it, the last row reappearing after a small scroll back starts a second request for the same page. - **`hasMore`**: once the server returns an empty page, the end of the feed is reached and further triggers do nothing. - **A cursor from the data**, such as the last post's id, rather than a page counter the view increments. The view never decides which page to fetch. ## Traps that cause stalls or double loads | Symptom | Cause | Fix | |---|---|---| | Every page loads at launch | Rows sit in a `VStack`, so all are created at once | Use a `LazyVStack` | | Same page requested twice | No in-flight guard; the last row appeared twice | Guard with `isLoading` in the model | | Loading stops after a short page | Trigger hung on a spinner after the `ForEach` that never left the screen, so `onAppear` never ran again | Trigger from the last post row, whose identity changes with each page | | Rows jump or duplicate | Page replaced the array, or ids repeat across pages | Append, and keep ids unique and stable | The short-page case is worth understanding. If the trigger is a spinner placed after the `ForEach` and shown whenever `hasMore` is true, its `onAppear` runs once, when it first appears. If the next page is short, the spinner never leaves the screen, so it never "appears" again, and loading stalls. With the per-row check, appending a short page puts a **new** last post on screen, whose `onAppear` runs and asks for the next page. ## Visibility-based triggers on iOS 18 From iOS 18, `onScrollVisibilityChange(threshold:_:)` calls its action when a view crosses a visibility threshold (half visible by default) inside its scroll view, and calls it on appearance if the threshold is already met. Attached to the last row or a footer, it fires on real visibility rather than creation. Many apps still deploy to iOS 17, where the `onAppear` pattern is the baseline; `onScrollGeometryChange(for:of:action:)`, also iOS 18, can instead compute the distance to the bottom from the scroll geometry. ## Reviewing a pagination change When a pull request adds or changes infinite loading, these are the questions worth asking: - Is the container a `LazyVStack` (or `List`), so the trigger depends on scrolling rather than on load? - Does the model, not the view, own `isLoading`, `hasMore` and the cursor? - Does an empty page set `hasMore` to false, while a failed request leaves it true, so the next appearance of the last row retries? - Are ids unique across pages, so a post returned twice by the server does not produce two rows with one identity? - Is there a visible loading row, and does it disappear when loading ends? ## What stays elsewhere - The choice between `onAppear` and `task`, and how `task` is cancelled, belongs to the lesson on view appearance and async work. - Cursor design, page sizes and caching on the server side belong to mobile system design. - Row identity rules for `ForEach` belong to the lesson on view identity.
- How would you start loading before the reader actually reaches the last post?Widen the check: fire when the appearing post is among the last few in the array, for example its index is within five of the end. Because the model ignores triggers while a load is in flight, several near-end rows appearing in a row cost nothing extra, and the next page usually arrives before the reader hits the bottom.
- Why is appending better than rebuilding the posts array after each page?Appending leaves existing elements and their ids untouched, so SwiftUI keeps the rows that already exist and the reader's position does not move. Rebuilding with new ids, for example freshly generated UUIDs, makes SwiftUI treat every row as new, which resets row state and can make the scroll view jump.
- What would you use on iOS 18 instead of onAppear for the trigger?onScrollVisibilityChange(threshold:_:) on the last row or a footer, which reports when the view crosses a visibility threshold inside its scroll view, half visible by default. It reacts to real on-screen visibility rather than to creation, but it needs iOS 18, so an iOS 17 deployment target keeps the onAppear pattern.
- Putting the posts in a VStack is fine because onAppear waits for scrolling.
- The view should track a page counter and decide which page to fetch.
- A spinner after the ForEach re-runs onAppear whenever posts are appended.
- Duplicate requests are impossible because onAppear runs only once per row.
- Reloading the whole array after each page is the safest way to add posts.
Assumes an iOS 17 baseline; onScrollVisibilityChange and onScrollGeometryChange were added in iOS 18 and are optional refinements.