|
1 | 1 | import 'src/styles/Leaderboard.scss'; |
2 | 2 |
|
3 | | -import React from 'react'; |
| 3 | +import React, { useEffect, useState } from 'react'; |
4 | 4 | import { useTypedSelector } from 'src/commons/utils/Hooks'; |
5 | 5 | import { ContestLeaderboardRow, LeaderboardRow } from 'src/features/leaderboard/LeaderboardTypes'; |
6 | 6 |
|
7 | 7 | import { Role } from '../../../commons/application/ApplicationTypes'; |
| 8 | +import { useDispatch } from 'react-redux'; |
| 9 | +import LeaderboardActions from 'src/features/leaderboard/LeaderboardActions'; |
8 | 10 |
|
9 | | -type Props = |
10 | | - | { type: string; contest: string | undefined; data: ContestLeaderboardRow[] | undefined } |
11 | | - | { type: string; contest: string | undefined; data: LeaderboardRow[] }; |
| 11 | +type Props = { |
| 12 | + type: string |
| 13 | + contest?: string |
| 14 | + contestID?: number |
| 15 | +} |
| 16 | + |
| 17 | +const LeaderboardExportButton: React.FC<Props> = ({ type, contest, contestID }) => { |
| 18 | + |
| 19 | + // Retrieve relevant leaderboard data |
| 20 | + const [ exportRequested, setExportRequest ] = useState(false); |
| 21 | + const dispatch = useDispatch(); |
| 22 | + const data = (type == "overall") |
| 23 | + ? useTypedSelector(store => store.leaderboard.userXp) |
| 24 | + : (type == "score") |
| 25 | + ? useTypedSelector(store => store.leaderboard.contestScore) |
| 26 | + : useTypedSelector(store => store.leaderboard.contestPopularVote); |
| 27 | + |
| 28 | + const onExportClick = () => { |
| 29 | + // Dispatch relevant request |
| 30 | + if (type == "overall") dispatch(LeaderboardActions.getAllUsersXp()); |
| 31 | + else if (type == "score") dispatch(LeaderboardActions.getAllContestScores(contestID as number)); |
| 32 | + else dispatch(LeaderboardActions.getAllContestPopularVotes(contestID as number)); |
| 33 | + setExportRequest(true) |
| 34 | + } |
| 35 | + |
| 36 | + // Return the CSV when requested and data is loaded |
| 37 | + useEffect(() => { |
| 38 | + if (exportRequested) { |
| 39 | + exportCSV(); |
| 40 | + setExportRequest(false); // Clear request |
| 41 | + } |
| 42 | + }, [data]) |
12 | 43 |
|
13 | | -const LeaderboardExportButton: React.FC<Props> = ({ type, contest, data }) => { |
14 | | - // pls remove this |
15 | | - if (!data) return; |
16 | 44 | const role = useTypedSelector(store => store.session.role); |
17 | 45 | const exportCSV = () => { |
18 | 46 | const headers = [ |
@@ -48,7 +76,7 @@ const LeaderboardExportButton: React.FC<Props> = ({ type, contest, data }) => { |
48 | 76 | }; |
49 | 77 |
|
50 | 78 | return role === Role.Admin || role === Role.Staff ? ( |
51 | | - <button onClick={exportCSV} className="export-button"> |
| 79 | + <button onClick={onExportClick} className="export-button"> |
52 | 80 | Export as .csv |
53 | 81 | </button> |
54 | 82 | ) : ( |
|
0 commit comments