简体   繁体   中英

PapaParse gets data in console.log but don't know how to make a new array that outputs on main screen on a table

New to PapaParse API. The data is shown on the console.log but I'm now trying to put that array in my component to make a table(will be using the MUI-Datatables API from https://material-ui.com/ ).

I don't know how to make a new array that I can display in my ReadingCSV Component. Any help is much much much appreciated!

Here is my code (with an image of the output at the bottom):

import React from "react";
import Papa from "papaparse";
import ReactDOM from "react-dom";

export async function GetData(info) {
  const dataInfo = Papa.parse(await fetchCSV(), {
    header: true,
    complete: results => {
      let x = [];
      x = results.data;
      console.log(x[1]);
    }
  });
  console.log(dataInfo);

  return dataInfo;
}

async function fetchCSV() {
  const response = await fetch("abc.csv");
  const reader = response.body.getReader();
  const result = await reader.read();
  const decoder = new TextDecoder("utf-8");
  const csv = await decoder.decode(result.value);
  // console.log("csv", csv);
  return csv;
}

GetData();

class ReadingCSV extends React.Component {
  render() {
    return (
      <div>
        <table>
          <thead>
            <tr>
              Name
              {/* {tableHeader.map(head => (
                <th>{head}</th>
              ))} */}
            </tr>
          </thead>
          <tbody>
            <tr>Test</tr>
          </tbody>
        </table>
      </div>
    );
  }
}

ReactDOM.render(<ReadingCSV />, document.getElementById("root"));

Current Output Screen with Console screen

I think you'll want to move your GetData and fetch functions inside the class, probably lose the export on the GetData function. Use consistent capitalization when naming your functions. GetData doesn't do anything with the info variable, lose it. Also delete complete callback since you're dataInfo variable will catch the data when parse completes.

Then you pretty much have it. Move the "GetData" call to the start of the reder() function and save the result: const myJSON = GetData() Then you just map over the data.

myJSON.map((row,index) => <tr key={index}><td>{row.fieldName}</td></tr>

Something along those lines. And rename "GetData" to "ParseCSVToJSON" or something that better reflects what it does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM