All files / src/components/fileOperator CsvPreview.tsx

100% Statements 15/15
100% Branches 6/6
100% Functions 5/5
100% Lines 15/15

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                                      1x 8x   8x 8x 8x   8x 4x     8x 4x                 4x 4x 4x         8x     2x               5x                
import React, { ReactElement, useEffect } from "react";
import { readString } from "react-papaparse";
import { Table } from "antd";
import { LargeSpin } from "../";
import { Store } from "antd/lib/form/interface";
 
type ResultType = {
  data: Array<Store>;
  meta: {
    aborted: boolean;
    cursor: number;
    delimiter: string;
    fields: Array<string>;
    linebreak: string;
    truncated: boolean;
  };
  errors: Array<string>;
};
 
const CsvPreview = (props: { data: string }): ReactElement => {
  const { data } = props;
 
  const [csvData, setCsvData] = React.useState<ResultType>({} as ResultType);
  const [headers, setHeaders] = React.useState<Array<string>>([]);
  const [loading, setLoading] = React.useState<boolean>(true);
 
  if (data == null) {
    console.warn(`data is ${data}, will treat it as ""(empty string) to render CSV preview`);
  }
 
  useEffect(() => {
    readString(data ?? "", {
      header: true,
      worker: true,
      comments: ";",
      delimiter: ",",
      skipEmptyLines: true,
      // eslint-disable-next-line @typescript-eslint/ban-ts-comment
      // @ts-ignore
      complete: (results: ResultType): void => {
        setHeaders(results.meta.fields);
        setCsvData(results);
        setLoading(false);
      }
    });
  }, [data]);
 
  return (
    loading ? <LargeSpin /> :
      <Table
        columns={headers.map((header: string) => ({
          title: header,
          dataIndex: header,
          key: header,
        }))}
        dataSource={csvData.data}
        pagination={{ position: ["bottomCenter", "bottomCenter"] }}
        rowKey={(record) => {
          return JSON.stringify(record);
        }}
      >
      </Table>
  );
};
 
export default CsvPreview;