Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Cannot read property 'map' of undefined with React

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"
        }
    ]
}
like image 911
JavaCake Avatar asked Mar 17 '23 23:03

JavaCake


1 Answers

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.

like image 74
nilgun Avatar answered Mar 19 '23 12:03

nilgun