Where the Next link comes from
Look at LIMIT 11 in the query below. A page in the Journal only has room for ten articles. We’ll use the extra article to answer one question before we send the page to the browser.
Take one more than you need
Say there are twenty articles under the same tag. The first page takes ten. We’d like to draw a Next link there and leave it off the second page. We could count all twenty matches, but the view only needs to know whether there’s one more. A cursor can also be useful if the list grows large.
Read the page number
Open the tag in a tab and look at the query string. The operation has an optional page as well as a tag. Both go into the generated query record. When the client leaves the page out, pick the default in the action. Give it a maximum too, since this value determines how many rows the database skips.
Here we accept a page number from zero to one thousand.
name: page
in: query
schema: {type: integer, minimum: 0, maximum: 1000}Try it with twenty articles
Read OFFSET 10 first. It skips articles one to ten. That leaves ten rows to return, even though we asked for eleven. Now suppose there’s a twenty-first article. The query returns eleven rows this time. Keep that last row out of the list and draw Next.
The ID in the sort order breaks ties between articles with the same timestamp. An insert between clicks can still move a row across an offset boundary. If you switch to a cursor, include the date and ID.
ORDER BY created_at DESC, id DESC
LIMIT 11 OFFSET 10Carry the tag into the link
Build the link with the tag you read from this GET and the new page number. Try copying its address and opening it in a different tab. You should land on the same slice of the same tag, even in a tab that never opened the first page.
In this view the selected tag and next page are already in scope. Watch where each goes in the call to url.
<a href={url("/?tag={selected}&page={next_page}")}>Next</a>