From fb52b25834b95ff9a11f8c7d3c20453e26d3bd4f Mon Sep 17 00:00:00 2001 From: nsfisis Date: Tue, 22 Jul 2025 05:21:40 +0900 Subject: feat(frontend): Optimistically update read state --- frontend/src/components/ArticleItem.tsx | 35 ++++++++++++++++++++++++--------- 1 file changed, 26 insertions(+), 9 deletions(-) (limited to 'frontend') diff --git a/frontend/src/components/ArticleItem.tsx b/frontend/src/components/ArticleItem.tsx index e5a506f..8fb00b0 100644 --- a/frontend/src/components/ArticleItem.tsx +++ b/frontend/src/components/ArticleItem.tsx @@ -1,5 +1,6 @@ import { faCheck, faCircle } from "@fortawesome/free-solid-svg-icons"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; +import { useOptimistic } from "react"; import { useMutation } from "urql"; import type { GetReadArticlesQuery, @@ -24,10 +25,22 @@ export function ArticleItem({ article, showReadStatus = true }: Props) { const [, markArticleRead] = useMutation(MarkArticleReadDocument); const [, markArticleUnread] = useMutation(MarkArticleUnreadDocument); + const [optimisticArticle, setOptimisticArticle] = useOptimistic( + article, + (currentArticle, newReadState: boolean) => ({ + ...currentArticle, + isRead: newReadState, + }), + ); + const handleToggleRead = async ( articleId: string, isCurrentlyRead: boolean, ) => { + const newReadState = !isCurrentlyRead; + + setOptimisticArticle(newReadState); + if (isCurrentlyRead) { await markArticleUnread({ id: articleId }); } else { @@ -38,7 +51,9 @@ export function ArticleItem({ article, showReadStatus = true }: Props) { const handleArticleClick = async (article: Article) => { // Open article in new tab and mark as read if it's unread window.open(article.url, "_blank", "noreferrer"); - if (!article.isRead) { + if (!optimisticArticle.isRead) { + setOptimisticArticle(true); + await markArticleRead({ id: article.id }); } }; @@ -46,7 +61,7 @@ export function ArticleItem({ article, showReadStatus = true }: Props) { return (
handleToggleRead(article.id, article.isRead)} + onClick={() => handleToggleRead(article.id, optimisticArticle.isRead)} className={`flex-shrink-0 rounded p-1 transition-colors ${ - article.isRead + optimisticArticle.isRead ? "text-gray-400 hover:text-gray-600" : "text-blue-600 hover:text-blue-700" }`} - title={article.isRead ? "Mark as unread" : "Mark as read"} + title={optimisticArticle.isRead ? "Mark as unread" : "Mark as read"} > @@ -71,13 +86,15 @@ export function ArticleItem({ article, showReadStatus = true }: Props) {
-- cgit v1.2.3-70-g09d2