TypeError: Cannot read property 'map' of undefined react ant design table

1.3k views Asked by At

friends im having a hard time finding the fix on this. i always gets an error

Cannot read property 'map' of undefined react ant design table. even when i try to console.log my returned object theres a data its not empty. but im getting an error. which i guess the error leads that my props is empty.

parent container get data from api:

<TabPane style={{ marginTop: 20 }} tab="My Settlements" key="1" >
  <MySettlements settlementprops={this.state.settlements} />
</TabPane>

the component handle the object from api

render() {
    const settlementprops = this.props.settlementprops;

    const tableData = settlementprops.map((obj) => ({
        campaign_name: obj.campaign_name
    }))

    const columns = [{
        title: 'Campaign Name',
        dataIndex: 'campaign_name',
        key: 'campaign_name',
      }
    ];

    var tableViewDom = [];
    tableViewDom.push(
            <Table
                className='my_campaigns_table'
                columns={columns} dataSource={tableData}
            > 
            </Table>
     )
2

There are 2 answers

0
lomse On BEST ANSWER

Change

const settlementprops = this.props.settlementprops;

To

const settlementprops = this.props.settlementprops || []
0
zimmerbimmer On

You are probably loading your data from API in componentDidMount which triggers after the first render. Whatever is your variable, just short circuit it like this:

this.state.myArray && this.state.myArray.map(...)

This way, if this.state.myArray does not have value, it won't try to map it over, which would fix your problem.