fireproof-storage / fireproof-storage/fireproof

Typescript Generics in react-hooks

Open
#81 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
973
Forks
58
PR merge metrics
No merged PRs in 30d

Description

First of all great project and I'm excited for the work ongoing in this space and this project in particular!

I'm following the vite/react tutorial [here](https://use-fireproof.com/docs/react-tutorial/) and ran into issues with the typescript compiler:

![image](https://github.com/fireproof-storage/fireproof/assets/2739322/28677686-9362-4d41-9bbb-affb3fa69aa5)

Switching to an interface and extending `DocBase` gets past this hurdle:

![image](https://github.com/fireproof-storage/fireproof/assets/2739322/c589972c-af33-404c-bd9d-5026afffcf8e)

However, the types returned by the `useDocument` hook are inferred as `DocBase` leading to a lot of casting when using the `todo` object as an actual instance of `ToDo` later on in the react component.

I expected there to be a version such as `useDocument(...)` and looking through the source for `useFireProof.tsx` there does appear to be comments alluding to this, but such signature doesn't appear to exist. I understand there has been some recent work regarding generics in #80 so maybe this is due to come. Either that or I'm using it wrong.
![image](https://github.com/fireproof-storage/fireproof/assets/2739322/cb205d33-5312-4092-87bc-6d73e159eb92)

The siutation is the same for `useLiveQuery`.

Finally, a tangent but related - whilst digging around the source I noticed that we have generic signatures for most functions on `database.ts` except `subscribe`. It's my understanding that this function will listen for all changes that occurred in the database since the latest clock sync with which documents of multiple types could have been changed.

Whilst working with other document databases, the common solution is to add a `type : string` field to each document and have a discriminator function map from the serialized JSON to the correct type at runtime. Would this be the recommendation when using fireproof e.g. handle it in the `(changes) => {...}` callback or is there scope to 'bake' this into the source by embedding the object type information into the JSON or providing an overload e.g:

```
type DocDiscriminator = (doc: DocBase) => boolean;

subscribe(listener: ListenerFn | NoUpdateListenerFn, updates?: boolean, discriminator?: DocDicriminator): () => void {
}
```

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.