]> git.localhorst.tv Git - gtbkgg-extension.git/blob - src/App/index.js
v0.0.1
[gtbkgg-extension.git] / src / App / index.js
1 import axios from 'axios';
2 import React from 'react';
3
4 import Leaderboard from './Leaderboard';
5 import './style.css';
6
7 const API_BASE = 'https://alttp.localhorst.tv/twitch/guessing-game-leaderboard';
8
9 const App = () => {
10         const [channelId, setChannelId] = React.useState('');
11         const [leaderboard, setLeaderboard] = React.useState({});
12         const [theme, setTheme] = React.useState('light');
13
14         React.useEffect(() => {
15                 window.Twitch.ext.onAuthorized((authCallback) => {
16                         setChannelId(authCallback.channelId);
17                 });
18                 window.Twitch.ext.onContext((context) => {
19                         if (context.theme) {
20                                 setTheme(context.theme);
21                         }
22                 });
23         }, []);
24
25         const fetchLeaderboard = React.useCallback(async (id) => {
26                 try {
27                         const rsp = await axios.get(`${API_BASE}/${id}/gtbk`);
28                         setLeaderboard(rsp.data);
29                 } catch (e) {
30                         setLeaderboard({});
31                 }
32         }, []);
33
34         React.useEffect(() => {
35                 if (channelId) {
36                         fetchLeaderboard(channelId);
37                         const interval = window.setInterval(() => {
38                                 fetchLeaderboard(channelId);
39                         }, 15 * 60 * 1000);
40                         return () => {
41                                 window.clearInterval(interval);
42                         };
43                 } else {
44                         setLeaderboard({});
45                 }
46         }, [channelId]);
47
48         if (!channelId) {
49                 return <div>loading</div>;
50         }
51
52         return <div className={`theme-${theme}`}>
53                 {leaderboard.all ?
54                         <Leaderboard entries={leaderboard.all} />
55                 :
56                         'No Leaderboard yet.'
57                 }
58         </div>;
59 };
60
61 export default App;