-
Notifications
You must be signed in to change notification settings - Fork 1
/
CSVUploadButton.tsx
78 lines (76 loc) · 2.42 KB
/
CSVUploadButton.tsx
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
import { UploadFile } from "@mui/icons-material"
import { Box, Button } from "@mui/material"
import { VisuallyHiddenInput } from "./VisuallyHiddenInput"
import React, { useState } from "react"
import VMD, { Table } from "../virtualmodel/VMD";
import { loadCSVToDB, validateCSV } from "../helper/CSVHelper";
import { parse } from "papaparse";
import { useDispatch, useSelector } from "react-redux";
import { displayError, displayNotification } from "../redux/NotificationSlice";
import Logger from "../virtualmodel/Logger";
import { RootState } from "../redux/Store";
interface CSVUploadButtonProps {
table: Table;
getRows: () => Promise<void>;
}
export const CSVUploadButton: React.FC<CSVUploadButtonProps> = ({ table, getRows }) => {
const dispatch = useDispatch();
const loggedInUser = useSelector((state: RootState) => state.auth.user);
function handleFileUpload(event: React.ChangeEvent<HTMLInputElement>) {
const file = event?.target?.files?.[0];
if (file) {
if (file.type !== 'text/csv') {
dispatch(displayError(`ERROR: '${file.name}' is not in CSV format.`))
}
else {
parse(file, {
header: true, skipEmptyLines: true, complete: async (result) => {
console.log(result);
try {
validateCSV(result, table);
await loadCSVToDB(result, table);
dispatch(displayNotification(`Succesfully loaded ${file.name} in table ${table.table_name}`));
const schema = VMD.getTableSchema(table.table_name);
Logger.logUserAction(
loggedInUser || "",
"Loaded CSV data",
`Loaded CSV data from ${file.name} (${result.data.length} rows)`,
schema?.schema_name || "",
table.table_name
);
getRows();
}
catch (error: any) {
if (error.response) {
dispatch(displayError(`ERROR: ${error.response.data.message}`))
}
else if (error instanceof Error) {
dispatch(displayError(`ERROR: ${error.message}`))
}
// Reset the value of the file input
}
}
})
}
event.target.value = '';
}
}
return <Button
component="label"
role={undefined}
variant="contained"
tabIndex={-1}
endIcon={<UploadFile fontSize="small" />}
style={{
backgroundColor: "#404040",
width: "fit-content",
marginTop: "",
display: "flex",
flexDirection: "row",
alignItems: "start"
}}
>
Upload CSV
<VisuallyHiddenInput type="file" accept=".csv" onChange={handleFileUpload} />
</Button>
}