Reputation: 63
I'm trying to get data from a document on the firebase database using FCM functions.
export const sendToDevicePaidBribe = functions.firestore
.document('PaidBribe/{bribeId}')
.onCreate(async snapshot => {
const report = snapshot.data();
const querySnapshot = await db
.collection('users')
.doc(report.uid).get();
const token = querySnapshot.data();
const payload: admin.messaging.MessagingPayload = {
notification: {
title: 'Report Submited!',
body: `Report id: ${report.id} on ${report.date}`,
icon: 'your-icon-url',
click_action: 'FLUTTER_NOTIFICATION_CLICK'
}
};
return fcm.sendToDevice(token.fcmToken, payload);
});
When I try to deploy the function it gives me the following error.
src/index.ts:48:30 - error TS2532: Object is possibly 'undefined'.
return fcm.sendToDevice(token.fcmToken, payload);
~~~~~
Can someone guide me as to why this error occurs?
Upvotes: 0
Views: 201
Reputation: 317712
Since Firestore doesn't give you a guarantee that any given document exists prior to querying it, you should check that yourself in code. Note from the API docs that snapshot.data() can return undefined in the event that the document doesn't exist. TypeScript is making you deal with that possibility of undefined in your code. You can do that by simply checking it before using it like this:
const token = querySnapshot.data();
if (token) {
// work with token safely here
}
Inside the if (token)
block, TypeScript assures you that token
can not possibly be undefined, and you are free to safely reference properties on it.
Upvotes: 1