react,redux,es6, firestore onsnapshot quering
I want to update a set of questions based on when a blog changes which itself changes when a category changes.
Ive managed to set the blog with firestore querying.
however when I try to chain onSnapshot with promises, the 2nd onSnapshot fails.
Im calling the 2nd onsnapshot together with update as the 2nd chain with promise all.
what isnt clear to me is why firestore doesnt find the document in the 2nd onSnapshot.
increment method is based on the firebase increment method:
firebase.firestore.FieldValue.increment()
every help is welcomed,
thanks in advance
my code:
all inside a redux toolkit thunk action:
export const getMainBlog = category => dispatch => {
...
}
setting paths for firestore to be used later:
const blogInCategoryCounter = firebase.db.collection(`categories/${category}/local-blogs`);
const getBlog = blogInCategoryCounter.orderBy("counterShownAllUsers","desc").limit(1)
const blogQuestionIndex =
firebase.db.collection("categories").doc(category).collection("blog-question-index");
first promise returned from function in the chain:
const getDoc = () => {
let promise = new Promise((resolve,reject) => {
getBlog.onSnapshot(snapshot => {
const data = snapshot.docs.map(doc => {
if (doc.exists){
return ({
id: doc.id,
...doc.data()
})
}else{
console.log("blog not found");
return null;
}
})
const [dataExtracted] = data
resolve(dataExtracted)
})
})
return promise;
}
2nd chain of promises including an update method and another onSnapshot:
const updateCounterBlog = data => {
let promise = new Promise((resolve,reject) => {
const returnedFromUpdate = blogInCategoryCounter.doc(data.id).update({
counterShownAllUsers: firebase.increment(1)
})
returnedFromUpdate.then(() => resolve(data))
})
return promise
}
const extractQuestionIndexQuestions = data => {
let promise = new Promise((resolve,reject) => {
blogQuestionIndex.doc(data.id).onSnapshot(doc => {
if (doc.exists){
resolve(doc.data())
}else{
reject("index doc not found")
}
})
})
return promise;
}
array of promises:
const promiseArray = [extractQuestionIndexQuestions,updateCounterBlog]
invocation:
getDoc().then(data => {
Promise.all(promiseArray.map(callback => callback(data))).then(values => {
const blog = {
blogData: data,
blogId: data.id,
category: category,
blogQuestionIndex: values[0]
}
dispatch(loadBlog(blog)) // for redux thunk
})
})
question from:
https://stackoverflow.com/questions/65952661/firestore-promise-chaining-2nd-chain-onsnapshot-cant-find-document