Reputation:
I am working on Push notifications on android via firebase cloud functions. My code is working absolutely nice when I use onWrite()
condition, I am trying to implement this function for commenting, but in this case when when someone edit or like comment it produces a notification, so I changed it to onCreate()
but now I am getting an error TypeError: Cannot read property 'val' of undefined
.
Here it is..
exports.pushNotificationCommentsPost = functions.database.ref('/post-comments/{postId}/{commentId}').onCreate((change, context) => {
const commentId = context.params.commentId;
const postId = context.params.postId;
const comment = change.after.val();
const posType = "Post";
const getPostTask = admin.database().ref(`/posts/${postId}`).once('value');
return getPostTask.then(post => {
// some code
})
});
I think there is a problem in const comment = change.after.val();
but I am unable to figure it out.
Upvotes: 3
Views: 4365
Reputation: 80924
You need to change this:
exports.pushNotificationCommentsPost = functions.database.ref('/post-comments/{postId}/{commentId}').onCreate((change, context) => {
into this:
exports.pushNotificationCommentsPost = functions.database.ref('/post-comments/{postId}/{commentId}').onWrite((change, context) => {
to work, since onWrite
triggers when data is created, updated, or deleted in the Realtime Database. Therefore you are able to retrieve the data before
and after
it changed.
onCreate()
triggers when new data is created in the Realtime Database. Therefore you can only retrieve the data that was newly added, example:
exports.dbCreate = functions.database.ref('/path').onCreate((snap, context) => {
const createdData = snap.val(); // data that was created
});
more info here:
https://firebase.google.com/docs/functions/beta-v1-diff#realtime-database
In your case, change it to this:
exports.pushNotificationCommentsPost = functions.database.ref('/post-comments/{postId}/{commentId}').onCreate((snap, context) => {
const commentId = context.params.commentId;
const postId = context.params.postId;
const comment = snap.val();
const posType = "Post";
});
Upvotes: 4