0

I am using React js to retrieve data.

Data.csv file location: /chart/data.csv

============ Date | id | No. 2021-Jan-2 | 1 | 3 2021-Jan-3 | 3 | 1 2021-Jan-4 | 4 | 4 2021-Jan-5 | 2 | 10 2021-Jan-6 | 6 | 7

Practice.js file location: /chart/Practice.js

I have tried to retrieve data from csv file and see in browser.

Here is how I have tried:

import React from 'react';
import * as d3 from 'd3';

const Practice = () => {
  const [data, setData] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    d3.csv("/data.csv").then((d) => {
      setData(d);
      setLoading(false);
    });
    return () => undefined;
  }, []);
  return (
        <div>
        <header>
            {loading && <div>loading</div>}
            {!loading && <div>data={data}</div>}
        </header>
        </div>
    );
}

export default Practice;

I keep getting an error message saying that TypeError: d3__WEBPACK_IMPORTED_MODULE_5__.csv(...).then is not a function

Am I using d3 correctly?

2
  • yo can use (github.com/iuccio/CSVtoJSON) Commented Mar 5, 2021 at 0:19
  • React runs in the context of your browser. Unless that file is a public/ file, your browser has no idea where that location is. Commented Mar 5, 2021 at 0:41

1 Answer 1

1

You need to either serve the file as a static asset if you wish to refer to it, or, for testing, use something you can find online....

Below is a sample using dome random csv I found on github.

Also, d3 returns an object which you cannot set as text in react. I have stringified it below...

import React from "react";
import * as d3 from "d3";

const Practice = () => {
  const [data, setData] = React.useState([]);
  const [loading, setLoading] = React.useState(true);

  React.useEffect(() => {
    d3.csv("https://raw.githubusercontent.com/curran/data/gh-pages/dbpedia/cities/properties.csv").then((d) => {
      setData(JSON.stringify(d, null, 2));
      setLoading(false);
    });
    return () => undefined;
  }, []);
  return (
    <div>
      <header>
        {loading && <div>loading</div>}
        {!loading && <pre>data={data}</pre>}
      </header>
    </div>
  );
};

export default Practice;
Sign up to request clarification or add additional context in comments.

Comments

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.