user1184205
user1184205

Reputation: 863

Firestore TimeStamp passed through Callable functions

I am working on a react web app that helps with project management. The issue I'm facing is around the timestamps of Firestore. Each project object stored in Firestore has a createdOn field that is of type Firestore timestamp. My web app is calling a callable firebase function which gets all the projects and returns them. The issue is the toDate() function doesn't work in the web app but it works in the firebase functions. I'm wondering if the problem is when converting to JSON that timeStamp loses something. Am I missing something or should I be storing them as something? I really don't want to convert all the dates server side as that would slow down the function call. I am using the timestamp to filter on the client side and for analytics.

How I'm writing the time stamp as part of the project object: createdOn: admin.firestore.Timestamp.now(),

and in the callable function I'm testing with this: console.log(allProjects[0].createdOn!.toDate()) and this works.

In my web app I'm calling this data.createdOn.toDate() and getting the error TypeError: data.createdOn.toDate is not a function

Any help would be appreciated. thanks,

I'm using on the functions side

"firebase-admin": "^8.0.0",
"firebase-functions": "^2.3.1",

and client side

"firebase": "^6.1.0",
"typescript": "^3.5.1"
"react": "^16.8.6",

Upvotes: 2

Views: 1170

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317322

"I'm wondering if the problem is when converting to JSON that timeStamp loses something."

Yes, it loses something. The Timestamp will be serialized in such a way that its seconds and nanoseconds fields will be sent individually. You will have to reconstitute a new Timestamp object from those values received on the client. Since you're not showing very specific code, it's not really possible to give more information. I strongly suggest you not just depend on the default JSON serialization of a Timestamp, and instead specifically read and write its seconds and nanoseconds fields explicitly on both ends.

See also this related question for Java: How to serialize Firestore TimeStamp in Android Java?

Upvotes: 4

Related Questions