SexyMF
SexyMF

Reputation: 11155

ReactJS race between componentWillMount and render functions

export class Dashboard extends React.Component<DashboardProps, IMonthlyCommission>{

    constructor(props) {
        super(props);
        this.state = {};
    }

    componentWillMount() {
        request.get("AffiliateCommissionStatement/GetCommissionDetails").send().end((err, res) => {
            var data: IMonthlyCommission = res.body.Commissions;
            this.setState(data);
        });
    }

    render() { 
       return <div>{this.state[0]}</div> ;
    }
}

Inside render, this.state[0] is null since the ajax call in componentWillMount is ASYNC.

How do I create a depenedncy between render and the ajax end function. So this way I won't get null exception/

Thanks

Upvotes: 0

Views: 58

Answers (1)

BravoZulu
BravoZulu

Reputation: 1140

You could make your render method handle the case where the data is not there yet:

render() {
  if (!this.state.data) 
    return <div>Loading...<div>

  return <div>{this.state.data[0]}</div>
}

Upvotes: 1

Related Questions