daydreamer daydreamer - 3 months ago 20
React JSX Question

React throwing error: Cannot read property 'map' of undefined

I am learning React. I am following a chapter in book where they load the data from API under

componentDidMount
and update the state of the component as

getInitialState: function () {
return {changeSets: []};
},
mapOpenLibraryDataToChangeSet : function (data) {
return data.map(function (change, index) {
return {
"when":jQuery.timeago(change.timestamp),
"who": change.author.key,
"description": change.comment
}
});
},
componentDidMount: function () {
$.ajax({
url: 'http://openlibrary.org/recentchanges.json?limit=10',
context: this,
dataType: 'json',
type: 'GET'
}).done(function (data) {
// console.log(data);
var changeSets = this.mapOpenLibraryDataToChangeSet(data);
console.log("changeSets:" + JSON.stringify(changeSets));
this.setState({changeSets: changeSets});
});
},


When I run this, I see error on console as

"TypeError: Cannot read property 'map' of undefined
at t.render (mikobuf.js:55:41)
at _renderValidatedComponentWithoutOwnerOrContext (https://npmcdn.com/react@15.3.1/dist/react.min.js:13:17508)
at _renderValidatedComponent (https://npmcdn.com/react@15.3.1/dist/react.min.js:13:17644)
at performInitialMount (https://npmcdn.com/react@15.3.1/dist/react.min.js:13:13421)
at mountComponent (https://npmcdn.com/react@15.3.1/dist/react.min.js:13:12467)
at Object.mountComponent (https://npmcdn.com/react@15.3.1/dist/react.min.js:15:2892)
at h.mountChildren (https://npmcdn.com/react@15.3.1/dist/react.min.js:14:26368)
at h._createInitialChildren (https://npmcdn.com/react@15.3.1/dist/react.min.js:13:26619)
at h.mountComponent (https://npmcdn.com/react@15.3.1/dist/react.min.js:13:24771)
at Object.mountComponent (https://npmcdn.com/react@15.3.1/dist/react.min.js:15:2892)"


The running link is http://jsbin.com/mikobuf/edit?js,console,output

What am I doing wrong?

UPDATE

When I added the
changeSets={data}
while rendering the app, I see data in console

ReactDOM.render(<App headings = {headings} changeSets={data}/>, document.getElementById("container"))


But I want the data to be pulled from
API
. So as soon as I remove the
changeSets={data}
when rendering, it fails

ReactDOM.render(<App headings = {headings}/>, document.getElementById("container"))

Answer

You are trying to use the props changeSets when it is actually part of Apps state.

This:

<RecentChangesTable.Rows changeSets={this.props.changeSets} />

Should Be:

<RecentChangesTable.Rows changeSets={this.state.changeSets} />

http://jsbin.com/tuqeciyere/1/edit?js,console,output