4wswt4ex2: Add like and unlike for post cards

This commit is contained in:
2026-10-19 14:16:52 -06:00
parent 20cca38619
commit 28037a2849
9 changed files with 402 additions and 5 deletions
+31
View File
@@ -2,6 +2,7 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { fetchFeedPage, FeedLoadError } from "@/lib/feed-client";
import { applyLikeOutcome, LikeError, sendLike } from "@/lib/like-client";
import { mergePosts, toCardPosts, type CardPost } from "@/lib/feed-model";
import { FeedView, type FeedStatus } from "./FeedView";
@@ -14,6 +15,8 @@ export function Feed({ onSignedOut }: { onSignedOut: () => void }) {
const [loadingMore, setLoadingMore] = useState(false);
const [loadMoreFailed, setLoadMoreFailed] = useState(false);
const [pending, setPending] = useState<CardPost[]>([]);
const [likeBusy, setLikeBusy] = useState<ReadonlySet<string>>(new Set());
const [likeErrors, setLikeErrors] = useState<ReadonlySet<string>>(new Set());
const sentinel = useRef<HTMLDivElement | null>(null);
const busy = useRef(false);
const shown = useRef<Set<string>>(new Set());
@@ -121,6 +124,31 @@ export function Feed({ onSignedOut }: { onSignedOut: () => void }) {
};
}, [status, fail]);
const toggleLike = useCallback(
async (post: CardPost) => {
if (!post.id) return;
const wanted = !post.isLiked;
const mark = (set: ReadonlySet<string>, on: boolean) => {
const next = new Set(set);
if (on) next.add(post.key);
else next.delete(post.key);
return next;
};
setLikeBusy((s) => mark(s, true));
setLikeErrors((s) => mark(s, false));
try {
const out = await sendLike(post.id, wanted);
setPosts((cur) => cur.map((p) => (p.key === post.key ? applyLikeOutcome(p, wanted, out) : p)));
} catch (e) {
fail(e instanceof LikeError && e.signedOut ? new FeedLoadError(true) : e);
setLikeErrors((s) => mark(s, true));
} finally {
setLikeBusy((s) => mark(s, false));
}
},
[fail],
);
function showNew() {
setPosts((cur) => mergePosts(cur, pending));
setPending([]);
@@ -136,6 +164,9 @@ export function Feed({ onSignedOut }: { onSignedOut: () => void }) {
newCount={pending.length}
onRetry={() => (status === "error" ? void loadFirst() : void loadMore())}
onShowNew={showNew}
onToggleLike={(p) => void toggleLike(p)}
likeBusy={likeBusy}
likeErrors={likeErrors}
sentinelRef={sentinel}
/>
);