-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseLike.ts
60 lines (48 loc) · 1.4 KB
/
useLike.ts
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
import axios from "axios";
import { useCallback, useMemo } from "react";
import { toast } from "react-hot-toast";
import useCurrentUser from "./useCurrentUser";
import useLoginModal from "./useLoginModal";
import usePost from "./usePost";
import usePosts from "./usePosts";
const useLike = ({ postId, userId }: { postId: string; userId?: string }) => {
const { data: currentUser } = useCurrentUser();
const { data: fetchedPost, mutate: mutateFetchedPost } = usePost(postId);
const { mutate: mutateFetchedPosts } = usePosts(userId);
const loginModal = useLoginModal();
const hasLiked = useMemo(() => {
const list = fetchedPost?.likedIds || [];
return list.includes(currentUser?.id);
}, [fetchedPost, currentUser]);
const toggleLike = useCallback(async () => {
if (!currentUser) {
return loginModal.onOpen();
}
try {
let request;
if (hasLiked) {
request = () => axios.delete("/api/like", { data: { postId } });
} else {
request = () => axios.post("/api/like", { postId });
}
await request();
mutateFetchedPost();
mutateFetchedPosts();
toast.success("Success");
} catch (error) {
toast.error("Something went wrong");
}
}, [
currentUser,
hasLiked,
postId,
mutateFetchedPosts,
mutateFetchedPost,
loginModal,
]);
return {
hasLiked,
toggleLike,
};
};
export default useLike;