Reputation: 21
I want to update isseen value to true when the sender is equal to "5" in below code. How can I update value of issen to true . My database structer is as below:
Chats
-LvuhnORi1ugp8U2Ajdq
isseen: "false"
message: "hi"
receiver: "OX0pReHXfXUTq1XnOnTSX7moiGp2"
sender: "5"
time: "16:23:22 12/12/2019"
-Lvuw34ZiXwD6UfWWeNm
isseen: "false"
message: "hi"
receiver: "OX0pReHXfXUTq1XnOnTSX7moiGp2"
sender: "7"
time: "17:17:22 12/12/2019"
i try this code but she only update one value of the first instance in my chat table and me i want to update the value of isseen to true when the sender equal to 5
SetSeen = ()=>{
var db = firebase.database();
var currentUser = firebase.auth().currentUser|| '';
var query= db.ref("Chats/"+currentUser.uid).orderByChild("sender").equalTo(this.props.inBox.inBox|| '');
query.once("child_added", function(snapshot) {
snapshot.ref.update({isseen: "true" })
});
}
can somebody help me
Upvotes: 2
Views: 149
Reputation: 26296
The reason your code only works for the first instance in your chat table is because you subscribe to the child_added
event only once:
query.once("child_added", function(snapshot) {
Changing this to on(...)
will re-trigger the function for each matching result.
query.on("child_added", function(snapshot) {
If possible, I would change your code so that the update to each isseen
value is atomic (all-or-nothing) and make use of promises to track any errors. This can be achieved using the following code:
SetSeen = () => {
const senderId = this.props.inBox.inBox;
const currentUser = firebase.auth().currentUser;
// fail-fast error handling
if (!senderId) {
return Promise.reject(new Error('Sender required'));
} else if (!currentUser) {
return Promise.reject(new Error('User required'));
}
// prepare query
var db = firebase.database();
var query = db.ref("Chats/"+currentUser.uid).orderByChild("sender").equalTo(senderId);
return query.once("value")
.then(queryResults => {
if (!queryResults.hasChildren()) {
return; // no results, nothing to update
}
var pendingUpdates = {};
// add each value to be updated
queryResults.forEach((chatSnapshot) => {
pendingUpdates[chatSnapshot.key + "/isseen"] = "true";
});
// commit changes
return queryResults.ref.update(pendingUpdates);
});
}
Upvotes: 0
Reputation: 80944
Change this:
var query= db.ref("Chats/"+currentUser.uid).orderByChild("sender").equalTo(this.props.inBox.inBox|| '');
into this:
var query= db.ref("Chats").orderByChild("sender").equalTo("5");
Add reference at node Chats
then orderByChild
will be able to access the attribute sender
, and you can use equalTo
to retrieve the data that you want
Upvotes: 1