Cannot Read Property map of undefined
You could try putting the users rendering logic in a method of your UserList class. Something close to this should work.
const UserList = React.createClass({
getInitialState: function () {
return {
users: []
}
},
componentDidMount: function () {
this.loadUsersFromServer();
},
loadUsersFromServer: function () {
axios.get('/api/users').then((users) => {
this.setState({users: users.data.users});
});
},
renderUsers: function (users) {
return <div>{users.map(user => <div key={user._id} username={user.username} />)}</div>
},
render: function () {
return (
<div>
<h1>User List</h1>
{ this.renderUsers(this.state.users) }
</div>
);
},
});
Comments
-
Taylor King almost 2 years
For some reason it sometimes maps through, but I get another error of not returning anything and other times it just says can't read property map of undefined. I'm trying to compile a list of users in React.
I have a component called UserList that is querying my database for all users and updating the state:
const UserList = React.createClass({ getInitialState: function () { return { users: [] } }, componentDidMount: function () { this.loadUsersFromServer(); }, loadUsersFromServer: function () { axios.get('/api/users').then((users) => { this.setState({users: users.data.users}); }); }, render: function () { return ( <div> <h1>User List</h1> <User users={this.state.users} /> </div> ); }, });
I'm then passing it to it's child component User, and that is where the error is coming into play:
const User = React.createClass({ render: function () { console.log('props: ' + JSON.stringify(this.props.users)); const users = this.props.users.map((user) => { return ( <User key={user._id} username={user.username} /> ); }); return ( <div id="users"> {users} </div> ); }, });
What is interesting in the Chrome Dev tools is that for some reason I get three logs when trying to print out the this.props.users, and I'm not sure why it logs out three, but the middle one has all the users I'm looking for:
Any help would be greatly appreciated!
-
Taylor King over 7 yearsThis doesn't solve the issue for me, unfortunately. :/ I had seen that suggested elsewhere as well, but I went ahead and tried it again. Still nothing.
-
Taylor King over 7 yearsYup! I believe that will work ... I'm going to rework this in a bit to do as such, and I will give you the answer. Thanks so much for pointing that out!
-
Tom Coughlin over 7 yearsNo problem! @TaylorKing
-
prosti over 7 yearsDoes this answer has sense @TaylorKing ?