2022-01-09 20:26:51 +00:00
|
|
|
import {
|
|
|
|
getDoc,
|
|
|
|
getDocs,
|
|
|
|
onSnapshot,
|
|
|
|
Query,
|
|
|
|
DocumentReference,
|
|
|
|
} from 'firebase/firestore'
|
|
|
|
|
2022-01-21 23:21:46 +00:00
|
|
|
export const getValue = async <T>(doc: DocumentReference) => {
|
|
|
|
const snap = await getDoc(doc)
|
2022-01-09 20:26:51 +00:00
|
|
|
return snap.exists() ? (snap.data() as T) : null
|
|
|
|
}
|
|
|
|
|
|
|
|
export const getValues = async <T>(query: Query) => {
|
|
|
|
const snap = await getDocs(query)
|
|
|
|
return snap.docs.map((doc) => doc.data() as T)
|
|
|
|
}
|
|
|
|
|
|
|
|
export function listenForValue<T>(
|
|
|
|
docRef: DocumentReference,
|
|
|
|
setValue: (value: T | null) => void
|
|
|
|
) {
|
2022-03-02 03:31:48 +00:00
|
|
|
// Exclude cached snapshots so we only trigger on fresh data.
|
|
|
|
// includeMetadataChanges ensures listener is called even when server data is the same as cached data.
|
|
|
|
return onSnapshot(docRef, { includeMetadataChanges: true }, (snapshot) => {
|
2022-01-30 05:05:32 +00:00
|
|
|
if (snapshot.metadata.fromCache) return
|
|
|
|
|
2022-01-09 20:26:51 +00:00
|
|
|
const value = snapshot.exists() ? (snapshot.data() as T) : null
|
|
|
|
setValue(value)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
export function listenForValues<T>(
|
|
|
|
query: Query,
|
|
|
|
setValues: (values: T[]) => void
|
|
|
|
) {
|
2022-03-02 03:31:48 +00:00
|
|
|
// Exclude cached snapshots so we only trigger on fresh data.
|
|
|
|
// includeMetadataChanges ensures listener is called even when server data is the same as cached data.
|
|
|
|
return onSnapshot(query, { includeMetadataChanges: true }, (snapshot) => {
|
2022-01-15 01:12:38 +00:00
|
|
|
if (snapshot.metadata.fromCache) return
|
|
|
|
|
2022-01-09 20:26:51 +00:00
|
|
|
const values = snapshot.docs.map((doc) => doc.data() as T)
|
|
|
|
setValues(values)
|
|
|
|
})
|
|
|
|
}
|