Skip to content

Commit 39756cc

Browse files
committed
feat(bind): wait for refs when binding a collections
1 parent 760d23c commit 39756cc

File tree

2 files changed

+27
-3
lines changed

2 files changed

+27
-3
lines changed

src/index.js

+27-2
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,9 @@ function bindCollection ({
6464
}) {
6565
// TODO wait to get all data
6666
const array = vm[key] = []
67-
resolve = callOnceWithArg(resolve, () => vm[key])
67+
const originalResolve = resolve
68+
// resolve = callOnceWithArg(resolve, () => vm[key])
69+
let isResolved
6870

6971
const change = {
7072
added: ({ newIndex, doc }) => {
@@ -79,7 +81,7 @@ function bindCollection ({
7981
target: array,
8082
key: newIndex,
8183
depth: 0,
82-
resolve
84+
resolve: resolve.bind(null, doc)
8385
})
8486
},
8587
modified: ({ oldIndex, newIndex, doc }) => {
@@ -93,9 +95,32 @@ function bindCollection ({
9395
}
9496
}
9597

98+
// TODO return custom unbind function that unbinds nested refs
9699
return collection.onSnapshot(({ docChanges }) => {
97100
// console.log('pending', metadata.hasPendingWrites)
98101
// docs.forEach(d => console.log('doc', d, '\n', 'data', d.data()))
102+
// NOTE this will only be triggered once and it will be with all the documents
103+
// from the query appearing as added
104+
// (https://firebase.google.com/docs/firestore/query-data/listen#view_changes_between_snapshots)
105+
if (!isResolved && docChanges.length) {
106+
// isResolved is only meant to make sure we do the check only once
107+
isResolved = true
108+
let count = 0
109+
const expectedItems = docChanges.length
110+
const validDocs = docChanges.reduce((dict, { doc }) => {
111+
dict[doc.id] = false
112+
return dict
113+
}, Object.create(null))
114+
resolve = ({ id }) => {
115+
if (id in validDocs) {
116+
if (++count >= expectedItems) {
117+
originalResolve(vm[key])
118+
// noop
119+
resolve = () => {}
120+
}
121+
}
122+
}
123+
}
99124
docChanges.forEach(c => {
100125
// console.log(c)
101126
change[c.type](c)

test/refs-collections.spec.js

-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ function delayUpdate (ref, time = 0) {
3131
const onSnapshot = ref.onSnapshot.bind(ref)
3232
ref.onSnapshot = fn => onSnapshot(async (...args) => {
3333
await delay(time)
34-
console.log('I waited for', time)
3534
fn(...args)
3635
})
3736
}

0 commit comments

Comments
 (0)