@@ -55,14 +55,11 @@ import { UpdateData } from "firebase/firestore";
55
55
56
56
export function DisplayName({userId }: {userId: string }) {
57
57
58
- /** The returned user is typed as FsMutableDocument<User> */
58
+ /** Returns user as FsMutableDocument<User> */
59
59
const [user, isLoading] = useDocument (refs .users , userId );
60
60
61
61
function handleUpdate() {
62
- /**
63
- * Here you can only pass in properties that exist on the User type.
64
- * FieldValue is allowed to be used to set things like Timestamps.
65
- */
62
+ /** Here update is typed to User, and FieldValues are allowed */
66
63
user .update ({modifiedAt: FieldValue .serverTimestamp ()})
67
64
}
68
65
@@ -71,8 +68,7 @@ export function DisplayName({userId}: {userId: string}) {
71
68
}
72
69
73
70
/**
74
- * Here Typescript understands that user.data is available, and it is typed
75
- * correctly to User.
71
+ * Typescript knows that user.data is available, because isLoading is false.
76
72
*/
77
73
return <div onClick ={handleUpdate}>{user.data.displayName }< / div > ;
78
74
}
@@ -221,3 +217,34 @@ on top of the Firestore hooks from that library.
221
217
I plan to rewrite the code at some point because it can probably be simplified
222
218
and improved, but for now it allows us to rely on the functionality without
223
219
having to write tests.
220
+
221
+ ## Sharing Types Between Server and Client
222
+
223
+ When you share your document types between your server and client code, you
224
+ might run into a problem with the ` Timestamp ` type, because the web and server
225
+ SDKs currently have slightly incompatible types. The web timestamp has a
226
+ ` toJSON ` method which doesn't exist on the server.
227
+
228
+ The way I work around this, is by using a type alias called ` FsTimestamp ` in all
229
+ of my document types. Then, in each of the client-side or server-side
230
+ applications, I declare this type globally in a ` global.d.ts ` file.
231
+
232
+ For web it looks like this:
233
+
234
+ ``` ts
235
+ import type { Timestamp } from " firebase/firestore" ;
236
+
237
+ declare global {
238
+ type FsTimestamp = Timestamp ;
239
+ }
240
+ ```
241
+
242
+ For my server code it looks like this:
243
+
244
+ ``` ts
245
+ import type { Timestamp } from " firebase-admin/firestore" ;
246
+
247
+ declare global {
248
+ type FsTimestamp = Timestamp ;
249
+ }
250
+ ```
0 commit comments