I am trying to retrieve 2 queries and do a calculation between the two. But it is rather slow or returning undefined.
Sometimes it shows me the values, but that is usually after I refresh the app.
The first where, gives the amount of documents where field 'active' is true. Then the second part is checking the active and hasread fields and returns the amount.
This is the code I am using:
export default class Home extends React.Component {
constructor(props) {
super(props)
this.gettingAmount = false;
this.unsubscribe = null;
this.announce = firebase.firestore().collection('announcements');
this.state = {
newAnnouncements: 0,
}
}
componentDidMount() {
this.gettingAmount = true;
let countHasRead;
let countAnnounce;
this.unsubscribe = firebase.auth().onAuthStateChanged((user) => {
if (user) {
this.announce
.where('active', '==', true)
.get()
.then(snapshot => {
countAnnounce = snapshot.size;
});
this.announce
.where('active', '==', true)
.where('hasread.' + user.uid, '==', true)
.get()
.then(snapshot => {
countHasRead = snapshot.size;
})
.catch(err => {
console.log('Error getting documents', err);
});
setTimeout(() => {
console.log('second', countAnnounce, countHasRead);
if (this.gettingAmount) {
this.gettingAmount = false;
this.setState({newAnnouncements: countAnnounce - countHasRead});
AsyncStorage.setItem('newAnnouncements', JSON.stringify(countAnnounce - countHasRead));
}
}, 1000);
}
});
}
}
So the console.log('second')
shows either undefined or the query is really slow and does show the values of countAnnounce and countHasRead.
Is it something I am doing wrong? I am unsure why it is showing as undefined.
Please help.