Skip to content

Commit 0a23e34

Browse files
committed
feat: landing & watchlist brn optimist
1 parent d0c630b commit 0a23e34

File tree

2 files changed

+308
-255
lines changed

2 files changed

+308
-255
lines changed

components/books/BtnWatchlist.tsx

Lines changed: 25 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
'use client'
2-
import { useTransition } from 'react'
3-
import { BellMinus, BellRing, Loader } from 'lucide-react'
2+
import { startTransition, useOptimistic } from 'react'
3+
import { BellMinus, BellRing } from 'lucide-react'
44
import { Button } from '@/components/ui/button'
55
import {
66
addToWatchlistAction,
@@ -14,29 +14,36 @@ export default function BtnWatchlist({
1414
bookId: string
1515
isWatched: boolean
1616
}) {
17-
const [pending, startTransition] = useTransition()
17+
const [optimisticWatched, setOptimisticWatched] = useOptimistic(
18+
isWatched,
19+
(_, next: boolean) => next
20+
)
21+
22+
const onToggle = () => {
23+
const currentState = optimisticWatched
24+
const nextState = !currentState
1825

19-
const handleAdd = () =>
2026
startTransition(async () => {
21-
await addToWatchlistAction(bookId)
27+
setOptimisticWatched(nextState)
28+
29+
if (currentState) {
30+
await removeFromWatchlistAction(bookId)
31+
} else {
32+
await addToWatchlistAction(bookId)
33+
}
2234
})
23-
const handleRemove = () =>
24-
startTransition(async () => await removeFromWatchlistAction(bookId))
35+
}
2536

26-
if (isWatched) {
37+
if (optimisticWatched) {
2738
return (
2839
<Button
2940
variant="outline"
3041
className="w-full bg-transparent"
31-
onClick={handleRemove}
32-
disabled={pending}
42+
onClick={onToggle}
43+
aria-pressed={optimisticWatched}
3344
>
3445
<>
35-
{pending ? (
36-
<Loader className="mr-2 h-4 w-4 animate-spin" />
37-
) : (
38-
<BellMinus className="mr-2 h-4 w-4 text-destructive" />
39-
)}
46+
<BellMinus className="mr-2 h-4 w-4 text-destructive" />
4047
Remove from Watchlist
4148
</>
4249
</Button>
@@ -46,15 +53,11 @@ export default function BtnWatchlist({
4653
<Button
4754
variant="outline"
4855
className="w-full hover:bg-(--color-light-vibrant) hover:text-white dark:hover:bg-(--color-dark-vibrant) dark:hover:text-white"
49-
onClick={handleAdd}
50-
disabled={pending}
56+
onClick={onToggle}
57+
aria-pressed={optimisticWatched}
5158
>
5259
<>
53-
{pending ? (
54-
<Loader className="mr-2 h-4 w-4 animate-spin" />
55-
) : (
56-
<BellRing className="mr-2 h-4 w-4" />
57-
)}
60+
<BellRing className="mr-2 h-4 w-4" />
5861
Add to Watchlist
5962
</>
6063
</Button>

0 commit comments

Comments
 (0)