2022-05-12 15:07:10 +00:00
|
|
|
import { useEffect } from 'react'
|
|
|
|
import { useFirestoreDocumentData } from '@react-query-firebase/firestore'
|
|
|
|
import {
|
|
|
|
Contract,
|
2022-06-29 19:21:40 +00:00
|
|
|
contracts,
|
2022-10-12 12:24:22 +00:00
|
|
|
getContractFromId,
|
2022-05-12 15:07:10 +00:00
|
|
|
listenForContract,
|
|
|
|
} from 'web/lib/firebase/contracts'
|
2022-04-06 18:55:59 +00:00
|
|
|
import { useStateCheckEquality } from './use-state-check-equality'
|
2022-06-29 19:21:40 +00:00
|
|
|
import { doc, DocumentData } from 'firebase/firestore'
|
2022-10-12 12:24:22 +00:00
|
|
|
import { useQuery } from 'react-query'
|
2021-12-09 22:05:55 +00:00
|
|
|
|
|
|
|
export const useContract = (contractId: string) => {
|
2022-05-12 15:07:10 +00:00
|
|
|
const result = useFirestoreDocumentData<DocumentData, Contract>(
|
|
|
|
['contracts', contractId],
|
2022-06-29 19:21:40 +00:00
|
|
|
doc(contracts, contractId),
|
2022-05-12 15:07:10 +00:00
|
|
|
{ subscribe: true, includeMetadataChanges: true }
|
2021-12-09 23:23:21 +00:00
|
|
|
)
|
2021-12-09 22:05:55 +00:00
|
|
|
|
2022-05-12 15:07:10 +00:00
|
|
|
return result.isLoading ? undefined : result.data
|
2021-12-09 23:23:21 +00:00
|
|
|
}
|
2021-12-16 06:36:51 +00:00
|
|
|
|
2022-10-12 12:24:22 +00:00
|
|
|
export const useContractsFromIds = (contractIds: string[]) => {
|
|
|
|
const contractResult = useQuery(['contracts', contractIds], () =>
|
|
|
|
Promise.all(contractIds.map(getContractFromId))
|
|
|
|
)
|
|
|
|
const contracts = contractResult.data?.filter(
|
|
|
|
(contract): contract is Contract => !!contract
|
|
|
|
)
|
|
|
|
|
|
|
|
return contractResult.isLoading ? undefined : contracts
|
|
|
|
}
|
|
|
|
|
2022-06-13 16:04:56 +00:00
|
|
|
export const useContractWithPreload = (
|
|
|
|
initial: Contract | null | undefined
|
|
|
|
) => {
|
|
|
|
const [contract, setContract] = useStateCheckEquality<
|
|
|
|
Contract | null | undefined
|
|
|
|
>(initial)
|
2022-04-06 17:32:57 +00:00
|
|
|
const contractId = initial?.id
|
2021-12-16 06:36:51 +00:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
if (contractId) return listenForContract(contractId, setContract)
|
2022-04-06 18:55:59 +00:00
|
|
|
}, [contractId, setContract])
|
2021-12-16 06:36:51 +00:00
|
|
|
|
|
|
|
return contract
|
|
|
|
}
|