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

I used a small test application in React to get data through AJAX, but it does not work as inteded, so I get the following error:

Uncaught TypeError: Cannot read property 'map' of undefinedInline JSX script

The code is as follows:

<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>

Answer from /api/bodyparts/:

{
    "bodyparts": [
        {
            "id": 1, 
            "name": "Face"
        }, 
        {
            "id": 3, 
            "name": "Mouth"
        }, 
        {
            "id": 2, 
            "name": "Nose"
        }
    ]
}
+4
source share
2 answers

With the initial render, this.state.bodypartsthere is undefined, therefore, the error you received.

you must return

{bodyparts:[]}

from getInitialState.

Also in your callback successyou should set the following state:

this.setState(data);

because your api is already returning bodypartsas part of its result.

+7
source

this.state.bodyparts - undefined. ajax.

0

All Articles