Personalized lists and viewer state
Open the same article in two accounts and mark it as a favorite in one. Both readers should see the same total, but only one should see the article marked as theirs.
Read the two values from SQL
Read the favorite count and the current reader’s selection in the same query. In the SQL below, look for the expression that counts all favorites and the one that uses the viewer’s ID. The Bend result gives the view a field for each.
Count favorites and read the current reader’s selection
Suppose Camille and Lou have both marked an article as a favorite. The count on the card should be two for everyone who opens the feed. To decide how to draw Lou’s button, the query needs one more answer. Is there a row with this article’s ID and Lou’s account ID?
This expression needs viewer_id and the article alias a in scope.
EXISTS (
SELECT 1 FROM article_favorites AS f
WHERE f.article_id = a.id AND f.user_id = ${viewer_id}
) AS favoritedShow posts by authors the reader follows
For the follow button, ask whether the pair exists with EXISTS. You can use that answer on the card without multiplying the article rows returned by the feed query.
Store the follower and the followed author as a unique pair. Bind the current reader’s ID in the query. A public GET for the global list can keep its own selection.
Add this predicate where the feed filters articles.
WHERE EXISTS (
SELECT 1 FROM follows AS f
WHERE f.follower = ${viewer_id} AND f.followed = a.author_id
)Let the URL choose the tab and page
Build the links with the profile, the selected tab and the page. A different reader can open the same list. Their button state still comes from their session.
The Journal has a separate typed GET for the favorites tab.
<a href={url("/profile/{username}/favorites")}>Favorites</a>Compare the result in two sessions
Open the Journal with two accounts. Favorite an article in one and compare the number and button in both windows. Auto Refresh reruns the read with the appropriate session.
In a development database, inspect the flag for one account separately from the total.
SELECT user_id, article_id FROM article_favorites ORDER BY user_id, article_id;