7
7
getDocFromCache ,
8
8
getDocFromServer ,
9
9
onSnapshot ,
10
+ SnapshotOptions ,
10
11
} from 'firebase/firestore' ;
11
12
import { useEffect , useMemo } from 'react' ;
12
13
import { useLoadingValue } from '../util' ;
@@ -120,13 +121,12 @@ export const useDocumentData = <T = DocumentData>(
120
121
docRef ?: DocumentReference < T > | null ,
121
122
options ?: DataOptions < T > & InitialValueOptions < T >
122
123
) : DocumentDataHook < T > => {
123
- const snapshotOptions = options ?. snapshotOptions ;
124
124
const [ snapshot , loading , error ] = useDocument < T > ( docRef , options ) ;
125
125
126
- const initialValue = options ?. initialValue ;
127
- const value = useMemo (
128
- ( ) => ( snapshot ?. data ( snapshotOptions ) ?? initialValue ) as T | undefined ,
129
- [ snapshot , snapshotOptions , initialValue ]
126
+ const value = getValueFromSnapshot (
127
+ snapshot ,
128
+ options ?. snapshotOptions ,
129
+ options ?. initialValue
130
130
) ;
131
131
132
132
const resArray : DocumentDataHook < T > = [ value , loading , error , snapshot ] ;
@@ -137,16 +137,15 @@ export const useDocumentDataOnce = <T = DocumentData>(
137
137
docRef ?: DocumentReference < T > | null ,
138
138
options ?: OnceDataOptions < T > & InitialValueOptions < T >
139
139
) : DocumentDataOnceHook < T > => {
140
- const snapshotOptions = options ?. snapshotOptions ;
141
140
const [ snapshot , loading , error , loadData ] = useDocumentOnce < T > (
142
141
docRef ,
143
142
options
144
143
) ;
145
144
146
- const initialValue = options ?. initialValue ;
147
- const value = useMemo (
148
- ( ) => ( snapshot ?. data ( snapshotOptions ) ?? initialValue ) as T | undefined ,
149
- [ snapshot , snapshotOptions , initialValue ]
145
+ const value = getValueFromSnapshot (
146
+ snapshot ,
147
+ options ?. snapshotOptions ,
148
+ options ?. initialValue
150
149
) ;
151
150
152
151
const resArray : DocumentDataOnceHook < T > = [
@@ -172,3 +171,14 @@ const getDocFnFromGetOptions = (
172
171
return getDocFromServer ;
173
172
}
174
173
} ;
174
+
175
+ const getValueFromSnapshot = < T > (
176
+ snapshot : DocumentSnapshot < T > | undefined ,
177
+ options ?: SnapshotOptions ,
178
+ initialValue ?: T
179
+ ) : T | undefined => {
180
+ return useMemo (
181
+ ( ) => ( snapshot ?. data ( options ) ?? initialValue ) as T | undefined ,
182
+ [ snapshot , options , initialValue ]
183
+ ) ;
184
+ } ;
0 commit comments