4

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"
        }
    ]
}

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Lack of coffee creates significant mistakes.
Which is better? creating an initial state on getInitialState {bodyparts:[]} or making an explicit conditional check when the this.state.bodyparts is set? like this. var bodypartItems = this.state.bodyparts && this.state.bodyparts.map(function (bodypart) { return ( <Bodypart name={bodypart.name} /> ); });
0

this.state.bodyparts is undefined. the component is rendering before the ajax has completed. Try setting an initial state

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.