react-query-firebase icon indicating copy to clipboard operation
react-query-firebase copied to clipboard

Firestore typescript does not work as documentation.

Open adithep opened this issue 3 years ago • 8 comments

https://codesandbox.io/s/amazing-borg-w0m79?file=/src/App.tsx

Check this code sandbox, you will see that ref is not assignable to useFirestoreQueryData as stated in documentation.

Type 'DocumentData' is not assignable to type 'Product'.

Am I doing something wrong or is there work around for this in the meanwhile?

adithep avatar Feb 15 '22 07:02 adithep

I have same issue.. any update on this?

Screen Shot 2022-02-24 at 1 07 24 PM e

Screen Shot 2022-02-24 at 1 07 40 PM

jimmysafe avatar Feb 24 '22 12:02 jimmysafe

@jimmysafe I think the way forward now is to use withConverter exclusively and not to use this library to inject any field into the doc anymore.

https://firebase.google.com/docs/reference/js/firestore_.firestoredataconverter

This is how I solved it.

export const firestoreConverter = <T extends Record<string, unknown>>() => ({
  toFirestore({ id, ...data }: PartialWithFieldValue<T>): DocumentData {
    return data
  },
  fromFirestore(snapshot: QueryDocumentSnapshot<T>, options: SnapshotOptions): T {
    const data = snapshot.data(options)
    return {
      id: snapshot.id,
      ...data,
    }
  },
})

adithep avatar Feb 28 '22 07:02 adithep

@adithep thanks very much, it works fine if i pass the whole object into the withConverter params:

Screen Shot 2022-02-28 at 11 22 07 AM

However if i pass the function firestoreConverter i get typescript error

Screen Shot 2022-02-28 at 11 23 26 AM

I guess i am probably passing the generic in a wrong way. Could you please show me how you have written the collection function?

jimmysafe avatar Feb 28 '22 10:02 jimmysafe

@jimmysafe collection(...).withConverter(firestoreConverter<Review>())

adithep avatar Feb 28 '22 10:02 adithep

@adithep i have tried that i get this. sad times :(

Screen Shot 2022-02-28 at 11 27 56 AM

Screen Shot 2022-02-28 at 11 29 06 AM

jimmysafe avatar Feb 28 '22 10:02 jimmysafe

Ok i kinda sorted by replacing the firestoreConverter function type params from <T extends Record<string, unknown>> to <T extends Record<string, any>> and now i get no errors and i get correct typings.

Screen Shot 2022-02-28 at 11 36 00 AM

@adithep thanks for the support, let me know if you know a better way of doing this 🥇

jimmysafe avatar Feb 28 '22 10:02 jimmysafe

@jimmysafe

Hey! There is a simple solution:

import { CollectionReference } from 'firebase/firestore'

const q = query(
  collection(db, 'task-lists') as CollectionReference<TaskListModel>
)

useFirestoreQuery(['task-lists'], q)

hoqpe avatar May 02 '22 16:05 hoqpe

@hoqpe Good solution! And doesn't mess up the code a lot.

jimmy-chiang avatar Aug 14 '22 07:08 jimmy-chiang