Load More with a Server Action
Hard · Server Actions
Build an infinite list with a Load more button, a common way to paginate in Next.js.
The page (a Server Component) already rendered the first 3 posts and passes them to your Client Component PostFeed, together with initialCursor and a Server Action getPosts(cursor). Server Actions are async functions that run on the server; the client calls them like normal functions and gets a Promise back (you can pass them to Client Components as props). Here the action is faked in the starter: after 30 ms it resolves to { posts, nextCursor }, where nextCursor is null when nothing is left.
- Render the posts as <li> items (text = title) inside <ul className="posts">. New posts are appended at the end.
- The button is <button className="more">. While a request runs it shows Loading… and is disabled; otherwise it shows Load more.
- Never start a second request while one is running, even if the button is clicked twice before React re-renders. A state update arrives too late for that; use a ref as a lock.
- A new post was published after the page was rendered, so the offset cursor now returns a post you already show. Skip posts whose id is already in the list.
- When nextCursor is null, remove the button and show <p className="end">No more posts</p>.
The footer Server calls: N is debug output from the starter that counts how often the action ran.
Tip: cursors based on ids (?after=42) avoid the duplicate problem completely; offsets are used here so you can see why it happens.