Reputation: 587
I've spent a long time trying to figure out what is the exact problem. I have a react component that fetches an array of users from a service then store it in the component state but I had hardcode it here for simplicity. when I run my page nothing shows up with no signs of errors in the console. I'm a newbie to react please bear with me.
here is my component :
var usersTable = React.createClass({
getInitialState: function() {
this.state = {
users: [],
dataResponse: []
};
return this.state;
},
getData: function() {
component.state.dataResponse.push({
name: "john doe",
email: "[email protected]",
job: "production manager",
id: 882771
});
component.state.dataResponse.push({
name: "jane doe",
email: "[email protected]",
job: "account manager",
id: 569811
});
//get the users from a service.
},
componentWillMount: function() {
this.getData();
if (this.state.dataResponse !== null && this.state.dataResponse !== undefined) {
var data = this.state.dataResponse;
for (var i = 0; i < data.length; i++) {
var tr = <tr>
<td> {
data[i].id
} </td> <td> {
data[i].name
} </td> <td> {
data[i].job
} </td> <td> {
data[i].email
} </td> </tr>;
this.state.users.push(tr);
}
}
},
render: function() {
return ( <table className = "table table-condensed"> {
this.state.users
} </table>);
}
});
ReactDOM.render( <usersTable /> , document.getElementById("usersComponentDiv"));
Plunk : https://plnkr.co/edit/CyYCgTArt7K5MLAbiCa7?p=preview
Upvotes: 0
Views: 46
Reputation: 7424
In order to change your component's state, use:
this.setState({
users: [...]
})
or
this.setState({
dataResponse: [...]
})
trying to use as this.state.users.push(..)
or this.state.dataResponse.push(...)
is not going to work.
I also noticed you are using state to save HTML
markup (such as td
and tr
) and this is not a good pattern due to performance reasons. It's better to keep only an array of objects with id
, name
, job
and email
only.
Remember that setState
is asynchronous and you will not have access to state's latest value right away if you try as:
this.setState({
users: [{ id: 1 }, { id: 2 }]
})
this.state.users // outdated version
Should you need access to its latest value, rather use:
this.setState({
users: [{ id: 1 }, { id: 2 }]
}, () => {
console.log(this.state) // new state version
})
In case you also need to access old state before update the new one, you also have the option:
this.setState(prevState => ({
users: [...prevState.users, { id: 3 }, { id: 4 }],
}), () => {
console.log(this.state) // new state
})
Upvotes: 1