Add instant feedback to like

This commit is contained in:
Ategon 2025-01-27 19:36:00 -05:00
parent 28461e257c
commit 2f71aa12ae

View file

@ -43,8 +43,8 @@ export default function LikeButton({ post }: { post: PostType }) {
: "", : "",
}} }}
onPress={async () => { onPress={async () => {
if (loading || liked) { if (!getCookie("token")) {
return; redirect("/login");
} }
setLoading(true); setLoading(true);
@ -66,49 +66,49 @@ export default function LikeButton({ post }: { post: PostType }) {
} }
); );
post.hasLiked = !post.hasLiked;
if (post.hasLiked) {
setLiked(true);
setTimeout(() => setLiked(false), 1000);
setLikes(likes + 1);
} else {
setLiked(false);
setLikes(likes - 1);
}
if (!response.ok) { if (!response.ok) {
setLoading(false); setLoading(false);
if (response.status == 401) { if (response.status == 401) {
redirect("/login"); redirect("/login");
} else { } else {
post.hasLiked = !post.hasLiked;
toast.error("An error occurred"); toast.error("An error occurred");
return; return;
} }
} else { } else {
const data = await response.json();
setLikes(parseInt(data.likes));
post.hasLiked = data.action === "like";
setLoading(false); setLoading(false);
setLiked(data.action === "like");
setTimeout(() => setLiked(false), 1000);
} }
}} }}
> >
{loading ? ( <div className="flex gap-2 items-center" style={{ position: "relative" }}>
<LoaderCircle className="animate-spin" size={16} /> <Heart size={16} />
) : ( <Heart
<div size={16}
className="flex gap-2 items-center" className={
style={{ position: "relative" }} liked && !reduceMotion
> ? "animate-ping absolute top-0 left-0"
<Heart size={16} /> : "absolute top-0 left-0"
<Heart }
size={16} style={{
className={ position: "absolute",
liked && !reduceMotion top: "0",
? "animate-ping absolute top-0 left-0" left: "0",
: "absolute top-0 left-0" zIndex: "10",
} }}
style={{ />
position: "absolute", <p>{likes}</p>
top: "0", </div>
left: "0",
zIndex: "10",
}}
/>
<p>{likes}</p>
</div>
)}
</Button> </Button>
); );
} }