Skip to content

Commit

Permalink
feat(bind): wait for refs when binding a collections
Browse files Browse the repository at this point in the history
  • Loading branch information
posva committed Dec 26, 2017
1 parent 760d23c commit 39756cc
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
29 changes: 27 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,9 @@ function bindCollection ({
}) {
// TODO wait to get all data
const array = vm[key] = []
resolve = callOnceWithArg(resolve, () => vm[key])
const originalResolve = resolve
// resolve = callOnceWithArg(resolve, () => vm[key])
let isResolved

const change = {
added: ({ newIndex, doc }) => {
Expand All @@ -79,7 +81,7 @@ function bindCollection ({
target: array,
key: newIndex,
depth: 0,
resolve
resolve: resolve.bind(null, doc)
})
},
modified: ({ oldIndex, newIndex, doc }) => {
Expand All @@ -93,9 +95,32 @@ function bindCollection ({
}
}

// TODO return custom unbind function that unbinds nested refs
return collection.onSnapshot(({ docChanges }) => {
// console.log('pending', metadata.hasPendingWrites)
// docs.forEach(d => console.log('doc', d, '\n', 'data', d.data()))
// NOTE this will only be triggered once and it will be with all the documents
// from the query appearing as added
// (https://firebase.google.com/docs/firestore/query-data/listen#view_changes_between_snapshots)
if (!isResolved && docChanges.length) {
// isResolved is only meant to make sure we do the check only once
isResolved = true
let count = 0
const expectedItems = docChanges.length
const validDocs = docChanges.reduce((dict, { doc }) => {
dict[doc.id] = false
return dict
}, Object.create(null))
resolve = ({ id }) => {
if (id in validDocs) {
if (++count >= expectedItems) {
originalResolve(vm[key])
// noop
resolve = () => {}
}
}
}
}
docChanges.forEach(c => {
// console.log(c)
change[c.type](c)
Expand Down
1 change: 0 additions & 1 deletion test/refs-collections.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@ function delayUpdate (ref, time = 0) {
const onSnapshot = ref.onSnapshot.bind(ref)
ref.onSnapshot = fn => onSnapshot(async (...args) => {
await delay(time)
console.log('I waited for', time)
fn(...args)
})
}
Expand Down

0 comments on commit 39756cc

Please sign in to comment.