0

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;
user229044
  • 232,980
  • 40
  • 330
  • 338

1 Answers1

0

In your sortBy function you are using tableData without destructuring it from state

sortBy(sort_attr) {
  const {tableData} = this.state;
  this.setState({
      tableData: tableData.sort('ascending')
      });
  }

However since you are updating currentState based on prevState, you should make use of functional setState like

sortBy(sort_attr) {
  this.setState(prevState => ({
      tableData: prevState.tableData.sort('ascending')
      }));
  }

Check this question for more info on when to use functional setState

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400