ReactJS Bind Data from Rest API to table

I am calling my rest endpoint to fetch data, which I can see is successfully being fetched and stored in the state. However the table is not displaying any data. Ideally I want it to work so that when the state is changed the table automatically refreshes.

import React from 'react';
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';

const parameterTypes = {
    0: 'STRING',
    1: 'BOOLEAN',
    2: 'INTEGETR',
    3: 'DECIMAL'
};

const categoryAvailable = {
    0: 'POS'
};

const options = {
    noDataText: 'No parameters founds.'
}

function enumFormatter(cell, row, enumObject) {
    return enumObject[cell];
}

export default class ParameterContainer extends React.Component {

    constructor() {
        super();
        this.state = { parameters: [] };
    }

    componentDidMount() {
        fetch('/api/parameters')
            .then(result => result.json())
            .then(params => {
                console.log(params);
                this.state.parameters = params;
                console.log(this.state);
            })
    }

    render() {
        return (
            <div>
                <h2>Parameters</h2>
                <BootstrapTable data={this.state.parameters} options={options}>
                    <TableHeaderColumn isKey dataField='id'>ID</TableHeaderColumn>
                    <TableHeaderColumn dataField='category' filterFormatted dataFormat={enumFormatter}
                                        formatExtraData={categoryAvailable} filter={{ type: 'SelectFilter', options: categoryAvailable }}>Category</TableHeaderColumn>
                    <TableHeaderColumn dataField='subCategory'>Sub Category</TableHeaderColumn>
                    <TableHeaderColumn dataField='parameter'>Parameter</TableHeaderColumn>
                    <TableHeaderColumn dataField='type' filterFormatted dataFormat={ enumFormatter }
                                       formatExtraData={parameterTypes} filter={{ type: 'SelectFilter', options: parameterTypes}}>Type</TableHeaderColumn>
                    <TableHeaderColumn dataField='roles'>Roles</TableHeaderColumn>
                </BootstrapTable>
            </div>
        )
    }
}

Answers:

Answer

You shouldn't mutate a component's state directly (only read from it). Use this.setState({parameters: params}) in order to play nicely with the component lifecycle.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.