I have a parent component named UsersTable
(it's a child of some other component and has users
and roles
as its props). The getRoles()
function is getting all the roles for a user using an ajax request. The result is returned to render()
and stores in allroles
variable. The problem is since Ajax is asynchronous, I'm not always getting the values I need in allroles
variable. It is sometimes empty or returns the same value for all users. I guess I should somehow use componentDidMount and componentWillReceiveProps according to descriptions. But I couldn't figure it out. Also, I think allroles
should be a state but doing that put the code in an infinite loop, and the browser keeps calling the ajax request forever!
Here is the parent component code:
export const UsersTable = React.createClass({
getRoles(){
var oneRole = "";
this.props.users.forEach(function(user){
server.getUserRoles(user.id,
(results) => {
this.oneRole =results['hits']['hits']
notifications.success("Get was successful ");
},
() => {
notifications.danger("get failed ");
});
}.bind(this));
return this.oneRole;
},
render() {
var rows = [];
var allroles = this.getRoles()
this.props.users.map(function(user) {
rows.push( <UserRow userID={user.id}
userEmail={user.email}
userRoles={allroles}
roles={this.props.roles} />);
}.bind(this));
return (
<table className="table">
<thead>
<tr>
<th>Email Address</th>
<th>Role</th>
<th>Edit</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
);
}
});
And here is the child component code:
export const UserRow = React.createClass({
var showRoles = this.props.userRoles.map((role) => <div> {role.description || ''}</div>);
render(){
return (
<tr>
<td>{this.props.userEmail}</td>
<td>{showRoles}</td>
</tr>
);
}
});