| 58 | |
| 59 | let childAddedHandler: ReturnType<typeof firebaseOnChildAdded> | undefined; |
| 60 | const onInitialLoad = (snapshot: DataSnapshot) => { |
| 61 | const snapshotVal = snapshot.val(); |
| 62 | let childrenToProcess = snapshotVal |
| 63 | ? Object.keys(snapshot.val()).length |
| 64 | : 0; |
| 65 | |
| 66 | // If the list is empty then initialise the hook and use the default `onChildAdded` behaviour |
| 67 | if (childrenToProcess === 0) { |
| 68 | childAddedHandler = firebaseOnChildAdded(ref, onChildAdded, onError); |
| 69 | onValue([]); |
| 70 | } else { |
| 71 | // Otherwise, we load the first batch of children all to reduce re-renders |
| 72 | const children: DataSnapshot[] = []; |
| 73 | |
| 74 | const onChildAddedWithoutInitialLoad = ( |
| 75 | addedChild: DataSnapshot, |
| 76 | previousKey?: string | null |
| 77 | ) => { |
| 78 | if (childrenToProcess > 0) { |
| 79 | childrenToProcess--; |
| 80 | children.push(addedChild); |
| 81 | |
| 82 | if (childrenToProcess === 0) { |
| 83 | onValue(children); |
| 84 | } |
| 85 | |
| 86 | return; |
| 87 | } |
| 88 | |
| 89 | onChildAdded(addedChild, previousKey); |
| 90 | }; |
| 91 | |
| 92 | childAddedHandler = firebaseOnChildAdded( |
| 93 | ref, |
| 94 | onChildAddedWithoutInitialLoad, |
| 95 | onError |
| 96 | ); |
| 97 | } |
| 98 | }; |
| 99 | |
| 100 | firebaseOnValue(ref, onInitialLoad, onError, { onlyOnce: true }); |
| 101 | const childChangedHandler = firebaseOnChildChanged( |