Complete the code to get the device token for push notifications.
const messaging = firebase.messaging();
messaging.getToken({ vapidKey: '[1]' })
.then((currentToken) => {
if (currentToken) {
console.log('Device token:', currentToken);
} else {
console.log('No registration token available.');
}
})
.catch((err) => {
console.log('An error occurred while retrieving token. ', err);
});The vapidKey is required to get the device token for push notifications in Firebase Cloud Messaging.
Complete the code to save the device token to Firestore under the user's document.
const db = firebase.firestore(); const userId = 'user123'; const token = [1]; db.collection('users').doc(userId).set({ deviceToken: token }, { merge: true });
The variable currentToken holds the device token retrieved from Firebase Messaging.
Fix the error in the code to correctly listen for token refresh events.
messaging.[1](() => { messaging.getToken().then((refreshedToken) => { console.log('Token refreshed:', refreshedToken); }).catch((err) => { console.log('Unable to retrieve refreshed token ', err); }); });
The correct Firebase Messaging method to listen for token refresh is onTokenRefresh.
Fill in the blank to correctly unsubscribe from push notifications and delete the token.
messaging.[1](currentToken).then(() => { console.log('Token deleted and unsubscribed successfully.'); }).catch((err) => { console.log('Error unsubscribing or deleting token:', err); });
Deleting the token using deleteToken unsubscribes from push notifications (including topics) and deletes the token.
Fill all three blanks to update the device token in Firestore only if the new token is different.
const db = firebase.firestore(); const userId = 'user456'; const newToken = [1]; const userRef = db.collection('users').doc(userId); userRef.get().then((doc) => { if (doc.exists && doc.data().deviceToken [2] [3]) { return userRef.update({ deviceToken: newToken }); } }).then(() => { console.log('Device token updated if changed.'); }).catch((error) => { console.error('Error updating token:', error); });
The code compares the existing deviceToken with the newToken and updates only if they are different.