I have implemented a little test application in React to fetch data via AJAX, but it is not working as inteded, hence i get following error:
Uncaught TypeError: Cannot read property 'map' of undefinedInline JSX script
Code is as following:
<div id="content"></div>
<script type="text/jsx">   
var Bodypart = React.createClass({
    render: function() {
        return (
            <div>
                {this.props.name}
            </div>
        )
    }
})    
var BodypartList = React.createClass({
    getInitialState: function() {
      return {data: []};
    },
    componentWillMount: function() {
      $.ajax({
        url: this.props.url,
        dataType: 'json',
        success: function(data) {
          this.setState({bodyparts: data});
        }.bind(this),
        error: function(xhr, status, err) {
          console.error(this.props.url, status, err.toString());
        }.bind(this)
      });
    },
    render: function() {
        var bodypartItems = this.state.bodyparts.map(function (bodypart) {
            return (
                <Bodypart 
                    name={bodypart.name} 
                />
            );
        });
        return (
        <div>
            {bodypartItems}
        </div>
        );
    }
});    
React.render(
    <BodypartList url="/api/bodyparts/" />,
    document.getElementById('content')
);
</script>
The response from /api/bodyparts/:
{
    "bodyparts": [
        {
            "id": 1, 
            "name": "Face"
        }, 
        {
            "id": 3, 
            "name": "Mouth"
        }, 
        {
            "id": 2, 
            "name": "Nose"
        }
    ]
}
                At initial render this.state.bodypartsis undefined hence the error you got.
you should return
{bodyparts:[]}
from getInitialState.
Also in your success callback you should set state like:
this.setState(data);
because your api already returns bodyparts as part of its result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With