useCollectionData & useCollectionDataOnce
Closed this issue ยท 7 comments
What are the options for useCollectionData & useCollectionDataOnce to receive the ID of each doc. In the react-firebase lib, the option was { idField: 'id' }. Was is the equivalent for firehooks?
Firestore has converters as a built-in feature. These converters allows transforming the data when reading and writing the data from/to Firestore (docs). With the rewrite of react-firebase-hooks, I wanted to avoid adding functionality that is anyway already provided by Firestore itself and therefore didn't include it.
In order to get the same behavior as { idField: 'id' }
, you have to define a converter and assign that converter to the document reference using .withConverter(...)
:
const ref = firestore.collection('...').doc('...');
const converter = {
toFirestore: (data) => data,
fromFirestore: (snap) => ({
id: snap.id,
...snap.data(),
}),
};
const [data] = useDocument(ref.withConverter(converter));
I understand that your approach of not adding existing functionality in a different form.
I made "withConverter(converter)" work without firehooks for both documents & collections. With useDocument it didn't work for me.
Oh, there is an error in the code above. It should be useDocumentData
and not useDocument
.
useDocument
only returns a snapshot and snap.data()
should then return the document data with the id.
I don't know, doesn't work for me. Not sure how to fix. For now I will just place the ID inside each document.
I also do not get why you're mixing V8 with V9 code ("const ref = firestore.collection('...').doc('...')")
I also do not get why you're mixing V8 with V9 code ("const ref = firestore.collection('...').doc('...')")
Muscle memory ๐. Sorry about that wrong code.
Full code should be
const ref = doc(firestore, 'collection', 'docId');
const converter = {
toFirestore: (data) => data,
fromFirestore: (snap) => ({
id: snap.id,
...snap.data(),
}),
};
const [data] = useDocumentData(ref.withConverter(converter));
Still figuring out why it doesn't work for me .. having Firehooks v 1.4.2 & Firebase v 9.1.3
No worries, thanks for your support!
Closing this then.
Feel free to reopen if the underlying issue is within the library.