-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
LikeButton.tsx
69 lines (63 loc) · 1.76 KB
/
LikeButton.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import { type FC, useEffect, useState } from "hono/jsx";
import { useDebounce } from "../hooks/useDebounce";
const LikeButton: FC = () => {
const [allCount, setAllCount] = useState(0);
const [count, setCount] = useState(0);
const [clicked, setClicked] = useState(false);
const value = useDebounce(count, 1000);
useEffect(() => {
(async () => {
const response = await fetch(
`${
import.meta.env.VITE_API_URL
}/like/${window.location.pathname.replace("/posts/", "")}`,
);
const res = await response.json<{ likes: number; slug: string }>();
setAllCount(res.likes);
})();
}, []);
useEffect(() => {
(async () => {
if (value === 0) {
return;
}
const response = await fetch(
`${
import.meta.env.VITE_API_URL
}/like/${window.location.pathname.replace("/posts/", "")}`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ increment: value }),
},
);
if (!response.ok) {
throw new Error(`Error: ${response.statusText}`);
}
})();
}, [value]);
const handleClick = () => {
setAllCount((e) => e + 1);
setCount((e) => e + 1);
setClicked(true);
setTimeout(() => {
setClicked(false);
}, 300);
};
return (
<div class="text-center mt-10">
<button
type="button"
onClick={handleClick}
className={`px-4 py-2 bg-gray-100 rounded-full w-36 h-36 text-7xl shadow-lg transform transition duration-500 ease-in-out ${
clicked ? "scale-110" : "scale-100"
}`}
>
👍
<br />
</button>
<p class="text-lg mt-3">{allCount}</p>
</div>
);
};
export default LikeButton;