Reputation: 123
i created a table in React.js, also I use Firebase for data storage, here is my table code
{tableData.map((row, index) => {
return (
<tr key={row + index}>
{row.map((cell, index) => {
return (
<td key={"cell_" + index} onClick={() => this.handleClick(this.state.userSurname)}>{cell}</td>
);
})}
</tr>
);
})}
and here is my this.setState
:
componentDidMount() {
db.onceGetUsers().on("child_added", snap =>{
var username = snap.child("name").child("name").val();
var surname = snap.child("name").child("surname").val();
this.setState({ users: this.state.users.concat([username])});
this.setState({ userSurname: this.state.userSurname.concat([surname])})
})
}
Here is my handleClick
function:
handleClick(event){
alert(event)
}
So.. here is my problem, alert dialog displays every user surname, and what I'm trying to do is to display surname of user that is clicked in table.. how can i do that? :)
Upvotes: 0
Views: 882
Reputation: 3127
You can achieve it like this, if you don't want to change your state structure:
handleClick(i){
alert(this.state.userSurname[i])
}
{tableData.map((row, i) => {
return (
<tr key={row + i}>
{row.map((cell, k) => {
return (
<td key={"cell_" + k} onClick={() => this.handleClick(i)}>{cell}</td>
);
})}
</tr>
);
})}
Upvotes: 2
Reputation: 80944
From the docs, child_added
:
Retrieve lists of items or listen for additions to a list of items. This event is triggered once for each existing child and then again every time a new child is added to the specified path. The listener is passed a snapshot containing the new child's data.
To display surname of only the user that clicked in table, you need to read data once, example:
db.onceGetUsers().once('value').then(snap)=> {
var username = snap.child("name").child("name").val();
var surname = snap.child("name").child("surname").val();
});
once
Listens for exactly one event of the specified event type, and then stops listening.
more info here:
https://firebase.google.com/docs/reference/js/firebase.database.Reference#once
Upvotes: 1