Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Can't Make an API call #36

Open
centrixsol opened this issue Aug 29, 2020 · 0 comments
Open

Can't Make an API call #36

centrixsol opened this issue Aug 29, 2020 · 0 comments

Comments

@centrixsol
Copy link

Can't make API call in Component Did mount in extended Table A. Its throwing an error cannot update state in unmounted component.
Cant-call-api

Here is my component

import React from 'react';
import { getUnits } from '../../../actions/unit';

import axios from 'axios';
import ENV from '../../../env';
import BootstrapTable from 'react-bootstrap-table-next';
import paginationFactory from 'react-bootstrap-table2-paginator';
import filterFactory, { Comparator, dateFilter } from 'react-bootstrap-table2-filter'
import ToolkitProvider from 'react-bootstrap-table2-toolkit';
import _ from 'lodash';
import faker from 'faker/locale/en_US';
import moment from 'moment';
import {
Container,
Row,
Col,
Badge,
Button,
CustomInput,
StarRating,
ButtonGroup
} from './../../../components';
import { CustomExportCSV } from '../pagination/CustomExportButton';
import { CustomSearch } from '../pagination/CustomSearch';
import { CustomPaginationPanel } from '../pagination/CustomPaginationPanel';
import { CustomSizePerPageButton } from '../pagination/CustomSizePerPageButton';
import { CustomPaginationTotal } from '../pagination/CustomPaginationTotal';
import { PageHeader } from '../pagination/PageHeader';
import { randomArray } from './../../../utilities';

const ProductQuality = {
Good: 'product-quality__good',
Bad: 'product-quality__bad',
Unknown: 'product-quality__unknown'
};

const sortCaret = (order) => {
if (!order)
return ;
if (order)
return <i className={fa fa-fw text-muted fa-sort-${order}}>
}

const INITIAL_PRODUCTS_COUNT = 25;
const generateRow = (index) => ({
_id: index,
unit: faker.commerce.productName(),
childUnit: randomArray([
ProductQuality.Bad,
ProductQuality.Good,
ProductQuality.Unknown
]),
convertRate: (1000 + Math.random() * 1000).toFixed(2),
status: Math.round(Math.random() * 6),
updatedAt: faker.date.past()
});

class Unit extends React.Component {

constructor() {
    super();
    this.state = {
        units: [],
        selected: [],
    };
    this.headerCheckboxRef = React.createRef();
}

componentDidMount() {
    this._isMounted = true;
    this.setState({
        units: {
            _id: 1,
            unit: "Kg",
            childUnit: "active",
            convertRate: "100",
            status: "Ok",

        }
    })
}

handleSelect(row, isSelected) {
    if (isSelected) {
        this.setState({ selected: [...this.state.selected, row._id] })
    } else {
        this.setState({
            selected: this.state.selected.filter(itemId => itemId !== row._id)
        })
    }
}

handleSelectAll(isSelected, rows) {
    if (isSelected) {
        this.setState({ selected: _.map(rows, '_id') })
    } else {
        this.setState({ selected: [] });
    }
}

handleAddRow() {
    const currentSize = this.state.units.length;

    this.setState({
        units: [
            generateRow(currentSize + 1),
            ...this.state.units,
        ]
    });
}

handleDeleteRow() {
    this.setState({
        units: _.filter(this.state.units, unit =>
            !_.includes(this.state.selected, unit._id))
    })
}

handleResetFilters() {
    this.nameFilter('');
    this.qualityFilter('');
    this.priceFilter('');
    this.satisfactionFilter('');
}

createColumnDefinitions() {
    return [{
        dataField: '_id',
        text: 'Unit ID',
        editable: false,
        headerStyle: () => {
            return { width: "15%" };
        }
    }, {
        dataField: 'unit',
        text: 'Unit Name',
        sort: true,
        sortCaret,
        editable: false,
        headerStyle: () => {
            return { width: "20%" };
        }
    }, {
        dataField: 'childUnit',
        text: 'Child Unit Name',
        editable: false,
        headerStyle: () => {
            return { width: "20%" };
        },
        sort: true,
        sortCaret,
    }, {
        dataField: 'convertRate',
        text: 'Conversion Rate',
        sort: true,
        sortCaret,
        editable: false,
        headerStyle: () => {
            return { width: "15%" };
        }
    }, {
        dataField: 'status',
        text: 'Status',
        sort: true,
        sortCaret,
        editable: false,
        headerStyle: () => {
            return { width: "15%" };
        }
    }, {
        dataField: 'updatedAt',
        text: 'Update At',
        formatter: (cell) =>
            moment(cell).format('DD/MM/YYYY'),
        editable: false,
        headerStyle: () => {
            return { width: "15%" };
        },
        sort: true,
        sortCaret
    }];
}

render() {

    const columnDefs = this.createColumnDefinitions();
    const paginationDef = paginationFactory({
        paginationSize: 5,
        showTotal: true,
        pageListRenderer: (props) => (
            <CustomPaginationPanel {...props} size="sm" className="ml-md-auto mt-2 mt-md-0" />
        ),
        sizePerPageRenderer: (props) => (
            <CustomSizePerPageButton {...props} />
        ),
        paginationTotalRenderer: (from, to, size) => (
            <CustomPaginationTotal {...{ from, to, size }} />
        )

    });
    const selectRowConfig = {
        mode: 'checkbox',
        selected: this.state.selected,
        onSelect: this.handleSelect.bind(this),
        onSelectAll: this.handleSelectAll.bind(this),
        selectionRenderer: ({ mode, checked, disabled }) => (
            <CustomInput type={mode} checked={checked} disabled={disabled} />
        ),
        selectionHeaderRenderer: ({ mode, checked, indeterminate }) => (
            <CustomInput type={mode} checked={checked} innerRef={el => el && (el.indeterminate = indeterminate)} />
        )
    };

    return (
        <Container>
            <PageHeader
                subTitle="Settings"
                subTitleLink="/allunits"
                title="All Units"
                buttonText="Add Unit"
            />
            <Row className="mb-5">
                <Col>
                    <ToolkitProvider
                        keyField="_id"
                        data={this.state.units}
                        columns={columnDefs}
                        search
                        exportCSV
                    >
                        {
                            props => (
                                <React.Fragment>
                                    <div className="d-flex justify-content-end align-items-center mb-2">
                                        <h6 className="my-0">
                                            All Units
                            </h6>
                                        <div className="d-flex ml-auto">
                                            <CustomSearch
                                                className="mr-2"
                                                {...props.searchProps}
                                            />
                                            <ButtonGroup>
                                                <CustomExportCSV
                                                    {...props.csvProps}
                                                >
                                                    Export
                                    </CustomExportCSV>
                                                <Button
                                                    size="sm"
                                                    outline
                                                    onClick={this.handleDeleteRow.bind(this)}
                                                >
                                                    Delete
                                    </Button>
                                                <Button
                                                    size="sm"
                                                    outline
                                                    onClick={this.handleAddRow.bind(this)}
                                                >
                                                    <i className="fa fa-fw fa-plus"></i>
                                                </Button>
                                            </ButtonGroup>
                                        </div>
                                    </div>
                                    <BootstrapTable
                                        rowStyle={{ backgroundColor: 'white' }}
                                        classes="table-responsive"
                                        pagination={paginationDef}
                                        filter={filterFactory()}
                                        selectRow={selectRowConfig}
                                        bordered={true}
                                        responsive={true}
                                        {...props.baseProps}
                                    />
                                </React.Fragment>
                            )
                        }
                    </ToolkitProvider>
                </Col>
            </Row>

        </Container >
    );
}

};

export default Unit;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
1 participant