-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhooks.ts
118 lines (95 loc) · 2.54 KB
/
hooks.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import { getUser, User } from "@soapboxsocial/minis.js";
import { useRouter } from "next/router";
import { useEffect, useRef, useState } from "react";
import { io, Socket } from "socket.io-client";
import { DefaultEventsMap } from "socket.io-client/build/typed-events";
import useSWR from "swr";
import { SERVER_BASE } from "./constants";
export function useSession() {
const [user, userSet] = useState<User>(null);
useEffect(() => {
async function getSession() {
try {
const _user = await getUser();
userSet(_user);
} catch (err) {
console.error(err);
}
}
if (typeof window !== "undefined") {
getSession();
}
}, []);
return user;
}
export function useSoapboxRoomId() {
const { query } = useRouter();
return (query?.roomID as string) || null;
}
export function useParams() {
const { query } = useRouter();
return {
isAppOpener: Boolean(query?.isAppOpener),
};
}
/**
*
* @param callback
* @param delay Delay amount in seconds
*/
export function useInterval(callback: Function, delay: number) {
const savedCallback = useRef<Function>();
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
function tick() {
savedCallback.current();
}
if (delay !== null) {
let id = setInterval(tick, delay * 1000);
return () => clearInterval(id);
}
}, [delay]);
}
const getTriviaCategories = async () => {
type Data = {
trivia_categories: {
id: number;
name: string;
}[];
};
const r = await fetch(`https://opentdb.com/api_category.php`);
const { trivia_categories }: Data = await r.json();
const cleaned = trivia_categories.map((val) => ({
label: val.name.replace("Entertainment: ", "").replace("Science: ", ""),
value: val.id.toString(),
}));
return cleaned;
};
export function useTriviaCategories() {
const { data } = useSWR("TriviaCategories", getTriviaCategories, {
refreshWhenHidden: false,
refreshWhenOffline: false,
revalidateOnFocus: false,
revalidateOnReconnect: false,
});
return data;
}
export function useSocket<
ListenEvents = DefaultEventsMap,
EmitEvents = DefaultEventsMap
>(namespace: string) {
const soapboxRoomId = useSoapboxRoomId();
const ref = useRef<Socket<ListenEvents, EmitEvents>>();
useEffect(() => {
if (typeof soapboxRoomId === "string") {
ref.current = io(SERVER_BASE + "/" + namespace, {
query: {
roomID: soapboxRoomId,
},
});
}
}, [soapboxRoomId]);
return ref.current;
}