forked from open-sauced/app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuseFollowUser.ts
57 lines (49 loc) · 1.63 KB
/
useFollowUser.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
import useSWR, { Fetcher, useSWRConfig } from "swr";
import { publicApiFetcher } from "lib/utils/public-api-fetcher";
import useSupabaseAuth from "./useSupabaseAuth";
interface FollowUserResponse {
data: DbFollowUser;
}
const useFollowUser = (username: string) => {
const { sessionToken, user } = useSupabaseAuth();
const { mutate: mutateGlobal } = useSWRConfig(); // adding this to mutate the global user data to update the users card status on follow/unfollow
const { data, error, mutate } = useSWR<FollowUserResponse, Error>(
username ? `users/${username}/follow` : null,
publicApiFetcher as Fetcher<FollowUserResponse, Error>
);
const follow = async () => {
const req = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/users/${username}/follow`, {
method: "PUT",
headers: {
Authorization: `Bearer ${sessionToken}`,
},
// eslint-disable-next-line no-console
}).catch((err) => console.log(err));
if (req && req.ok) {
mutate();
mutateGlobal(`user/${user?.user_metadata?.username}`);
}
};
const unFollow = async () => {
const req = await fetch(`${process.env.NEXT_PUBLIC_API_URL}/users/${username}/follow`, {
method: "DELETE",
headers: {
Authorization: `Bearer ${sessionToken}`,
},
// eslint-disable-next-line no-console
}).catch((err) => console.log(err));
if (req && req.ok) {
mutate();
mutateGlobal(`user/${user?.user_metadata?.username}`);
}
};
return {
data: data || undefined,
isLoading: !error && !data,
isError: !!error,
mutate,
follow,
unFollow,
};
};
export default useFollowUser;