11import { database } from 'firebase' ;
2- import { useEffect , useReducer , useRef , useState } from 'react' ;
2+ import { useEffect , useReducer } from 'react' ;
3+ import { useIsEqualRef } from '../util' ;
34
45export type ListHook = {
56 error ?: Object ;
6- list : database . DataSnapshot [ ] ;
77 loading : boolean ;
8+ value : database . DataSnapshot [ ] ;
89} ;
910
1011type KeyValueState = {
@@ -112,18 +113,7 @@ const reducer = (state: ReducerState, action: ReducerAction): ReducerState => {
112113export default ( query : database . Query ) : ListHook => {
113114 const [ state , dispatch ] = useReducer ( reducer , initialState ) ;
114115
115- const [ error , setError ] = useState ( false ) ;
116- const [ loading , setLoading ] = useState ( true ) ;
117- // Combine keys and values in a single state hook to allow them to be manipulated together
118- const [ { values } , setKeysValues ] = useState ( { keys : [ ] , values : [ ] } ) ;
119- // Set a ref for the query to make sure that `useEffect` doesn't run
120- // every time this renders
121- const queryRef = useRef ( query ) ;
122- // If the query has changed, then reset the state
123- if ( ! query . isEqual ( queryRef . current ) ) {
124- queryRef . current = query ;
125- dispatch ( { type : 'reset' } ) ;
126- }
116+ const ref = useIsEqualRef ( query , ( ) => dispatch ( { type : 'reset' } ) ) ;
127117
128118 const onChildAdded = (
129119 snapshot : database . DataSnapshot | null ,
@@ -149,16 +139,15 @@ export default (query: database.Query): ListHook => {
149139
150140 useEffect (
151141 ( ) => {
152- const query : database . Query = queryRef . current ;
142+ const query : database . Query = ref . current ;
153143 // This is here to indicate that all the data has been successfully received
154144 query . once (
155145 'value' ,
156146 ( ) => {
157- setLoading ( false ) ;
147+ dispatch ( { type : 'loading ' } ) ;
158148 } ,
159- ( err : object ) => {
160- setError ( err ) ;
161- setLoading ( false ) ;
149+ ( error : object ) => {
150+ dispatch ( { type : 'error' , error } ) ;
162151 }
163152 ) ;
164153 query . on ( 'child_added' , onChildAdded ) ;
@@ -173,13 +162,13 @@ export default (query: database.Query): ListHook => {
173162 query . off ( 'child_removed' , onChildRemoved ) ;
174163 } ;
175164 } ,
176- [ queryRef . current ]
165+ [ ref . current ]
177166 ) ;
178167
179168 return {
180- error,
181- list : values ,
182- loading ,
169+ error : state . error ,
170+ loading : state . loading ,
171+ value : state . value ,
183172 } ;
184173} ;
185174
0 commit comments