Reputation: 421
I have a function that gets called when a button on a search form is clicked. We get the string and check it to make sure it's letters only. We then check to see if the players name is already in the database or not, if it isn't, we add him. If he is in the database, we go to the else portion of the statement. This is working fine -- but in my else area, when we get to the point that we know for sure there is a player with the exact same name in the database, I want to manipulate one of the characteristics in the database for that player. Specifically, add 1 to the players vote count.
writePlayer(newPlayerContent){
if (/^[a-zA-Z\s]*$/.test(this.state.newPlayerContent)) {
this.checkIfUserExists(this.state.newPlayerContent);
if(this.state.duplicate !== true){
this.props.addPlayer(this.state.newPlayerContent);
this.setState({
newPlayerContent: '',
})
}
else{
var playersRef = firebase.database().ref();
playersRef.child('players').orderByChild("playerContent").equalTo(this.state.newPlayerContent).once("value",snapshot => {
const userData = snapshot.val();
console.log(userData)
})
}
}
else {
console.log("Non-letter character found in: " + this.state.newPlayerContent)
}
}
When I do that console.log(userData) I am getting relevant information for the specific player I want to manipulate -- such as
-KytHrvt8R1DkY0E4Fho: {playerContent: "Test", rank: 0, votes: 0}
I want to do a votes++ on the player in userData. I just can't figure out what to add into my else statement to change that fields data.
My Firebase is laid out like so:
players
playerContent: "Test"
rank: 0
votes: 0
Upvotes: 1
Views: 62
Reputation: 6900
Try this
else{
var playersRef = firebase.database().ref();
playersRef.child('players').orderByChild("playerContent").equalTo(this.state.newPlayerContent).once("value",snapshot => {
snapshot.forEach(child => {
const data = child.val();
const key = child.key
//set the vote count
playersRef.child('players/'+key).update({
votes: data.votes + 1;
});
});
})
}
you need to loop through the data to get the actual result, then use the key to point the desired player and set its value. hope this helps.
Upvotes: 2