forked from SashenJayathilaka/Airbnb-Build
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseFavorite.ts
56 lines (45 loc) · 1.3 KB
/
useFavorite.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
import { SafeUser } from "@/types";
import axios from "axios";
import { useRouter } from "next/navigation";
import { useCallback, useMemo } from "react";
import { toast } from "react-toastify";
import useLoginModel from "./useLoginModal";
type Props = {
listingId: string;
currentUser?: SafeUser | null;
};
function useFavorite({ listingId, currentUser }: Props) {
const router = useRouter();
const loginModel = useLoginModel();
const hasFavorite = useMemo(() => {
const list = currentUser?.favoriteIds || [];
return list.includes(listingId);
}, [currentUser, listingId]);
const toggleFavorite = useCallback(
async (e: React.MouseEvent<HTMLDivElement>) => {
e.stopPropagation();
if (!currentUser) {
return loginModel.onOpen();
}
try {
let request;
if (hasFavorite) {
request = () => axios.delete(`/api/favorites/${listingId}`);
} else {
request = () => axios.post(`/api/favorites/${listingId}`);
}
await request();
router.refresh();
toast.success("Success");
} catch (error: any) {
toast.error("Something Went Wrong");
}
},
[currentUser, hasFavorite, listingId, loginModel]
);
return {
hasFavorite,
toggleFavorite,
};
}
export default useFavorite;