I have a simple react component let user to upload csv file using react-csv-reader then upload it to database. How to assign csv data to state in react? I meet the error Import.jsx:23 Uncaught TypeError: Cannot read property 'state' of undefined when I read the data from state.
import React from "react";
import axios from "axios";
import PropTypes from 'prop-types';
import CSVReader from "react-csv-reader";
import "assets/css/import.css";
class Import extends React.Component {
constructor(props) {
super(props);
this.state = {data:[]};
}
handleForce = data => {
console.log(data.length);
console.log(data);
this.setState({data: data});
};
handleClick() {
console.log("success");
console.log(this.state.data);/*this is where error occur*/
}
render() {
return (
<div className="container">
<CSVReader
className="csv-input"
label="Select CSV file to import"
onFileLoaded={this.handleForce}
/>
<div>
</div>
<button onClick={this.handleClick}>
Upload
</button>
</div>
);
}
}
Import.propTypes = {
classes: PropTypes.object.isRequired,
};
export default Import;
It successfully print in console at line console.log(data.length); and console.log(data);. However, I think it fail to assign the csv data to state.
This is the csv data successfully printed in console.
0: (11) ["identifier", "postal", "volume", "weight", "service_time", "phone", "customer_name", "window_start", "window_end", "lat", "lng"]
1: (11) ["SN48164550", "089952", "1", "1", "15", "90648664", "Customer 860", "2018-10-11 10:00:00", "2018-10-11 13:00:00", "1.27601", "103.836"]
2: (11) ["SN78463977", "269836", "1", "1", "15", "92656072", "Customer 517", "2018-10-11 16:00:00", "2018-10-11 19:00:00", "1.31924", "103.797"]
3: (11) ["SN16822741", "559782", "1", "1", "15", "94274895", "Customer 202", "2018-10-11 12:00:00", "2018-10-11 15:00:00", "1.36392", "103.861"]