I am new to react and have problem sorting the datatable in react redered from json object. I have rendered the datatable properly, but when i try to sort my datatable by using onClick on the cell component,the error says "./src/App.js Line 34: 'tableData' is not defined no-undef".
Please point out what is the error I am making.The source code is :
import React from 'react';
import axios from 'axios';
import {Table, Column, Cell} from 'fixed-data-table-2';
import 'fixed-data-table-2/dist/fixed-data-table.css';
class App extends React.Component {
constructor (props) {
super(props);
this.state = { tableData : []};
this.sortBy = this.sortBy.bind(this);
}
sortBy(sort_attr) {
this.setState({
tableData: tableData.sort('ascending')
});
}
componentDidMount() {
axios.get('https://drupal8.sample.com/my-api/get.json', {
responseType: 'json'
}).then(response => {
this.setState({ tableData: response.data });
console.log(this.state.tableData);
});
}
render() {
const rows = this.state.tableData;
return (
<Table
rowHeight={50}
rowsCount={rows.length}
width={500}
height={500}
headerHeight={50}>
<Column
header={<Cell onClick= {this.sortBy}>resourceID</Cell>}
columnKey="resourceID"
cell={({ rowIndex, columnKey, ...props }) =>
<Cell {...props}>
{rows[rowIndex][columnKey]}
</Cell>}
width={200}
/>
<Column
header={<Cell>resourceType</Cell>}
columnKey="resourceType"
cell={({ rowIndex, columnKey, ...props }) =>
<Cell {...props}>
{rows[rowIndex][columnKey]}
</Cell>}
width={200}
/>
<Column
header={<Cell>tenantName</Cell>}
columnKey="tenantName"
cell={({ rowIndex, columnKey, ...props }) =>
<Cell {...props}>
{rows[rowIndex][columnKey]}
</Cell>}
width={200}
/>
</Table>
);
}
}
export default App;
In your
sortByfunction you are usingtableDatawithout destructuring it from stateHowever since you are updating
currentStatebased onprevState, you should make use offunctional setStatelikeCheck this question for more info on
when to use functional setState