4

I have tried using "papparse" but did not get exact data. What is wrong in my code?

I want using CSV file getting all data by JSON format and set into my hookState.

Code:

import React from "react";
import { Table, Tag, Space } from "antd";
import Papa from "papaparse";
function Home() {
  const [rows, setRows] = React.useState([]);
  React.useEffect(() => {
    async function getData() {
      const response = await fetch("../Assets/images/state_wise_data.csv");
      const reader = response.body.getReader();
      const result = await reader.read(); // raw array
      const decoder = new TextDecoder("utf-8");
      const csv = decoder.decode(result.value); // the csv text
      const results = Papa.parse(csv, { header: true }); // object with { data, errors, meta }
      const rows = results.data; // array of objects
      setRows(rows);
    }
    getData();
  }, []);
  console.log(rows);
  return (
    <div>
      <Table columns={columns} dataSource={rows} />
    </div>
  );
}
export default Home;
2
  • 1
    what you see on console.log(rows) Commented Nov 4, 2020 at 4:40
  • some html code like this ``` "<html lang="en">"} 1: {<!DOCTYPE html>: " <head>"} Commented Nov 4, 2020 at 4:47

1 Answer 1

5

as per the documentation this is the approach

React.useEffect(() => {
    Papa.parse("../Assets/images/state_wise_data.csv", {
        download: true,
        complete: data => {
            setRows(data.data);
        }
    });
}, []);

demo

if you are having errors check console.log(data); inside complete callback

here is a complete example

Sign up to request clarification or add additional context in comments.

3 Comments

Got it but its not a json format how to show data in table
@samliprajapati add new configuration header: true, and then first raw of the csv should be the headings stackblitz.com/edit/react-r5nxcn?file=src%2FApp.js
@samliprajapati here is a complete example stackblitz.com/edit/react-r5nxcn?file=src%2FApp.js

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.