Skip to content

Commit 221f5aa

Browse files
committed
Update readme
1 parent 8a0fce5 commit 221f5aa

File tree

1 file changed

+34
-7
lines changed

1 file changed

+34
-7
lines changed

README.md

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -55,14 +55,11 @@ import { UpdateData } from "firebase/firestore";
5555

5656
export function DisplayName({userId}: {userId: string}) {
5757

58-
/** The returned user is typed as FsMutableDocument<User> */
58+
/** Returns user as FsMutableDocument<User> */
5959
const [user, isLoading] = useDocument(refs.users, userId);
6060

6161
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 */
6663
user.update({modifiedAt: FieldValue.serverTimestamp()})
6764
}
6865

@@ -71,8 +68,7 @@ export function DisplayName({userId}: {userId: string}) {
7168
}
7269

7370
/**
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.
7672
*/
7773
return <div onClick={handleUpdate}>{user.data.displayName}</div>;
7874
}
@@ -221,3 +217,34 @@ on top of the Firestore hooks from that library.
221217
I plan to rewrite the code at some point because it can probably be simplified
222218
and improved, but for now it allows us to rely on the functionality without
223219
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

Comments
 (0)