I've tried implementing the solutions here:
Conditional where clause in firestore queries
Firestore: Multiple conditional where clauses
But they do not seem to work (see code examples below). Has Firestore changed anything? Am I messing up something in the code below?
Thanks in advance!
For context, the below is in a useEffect hook inside a react functional component. However, I do not believe that is relevant, as the working example below (without the conditional queries) works fine.
Basic example - filter hard coded - works fine. The filter is applied
const query = db.collection('todos')
.where('userId', '==', userId)
.where('status', '==', 'pending');
query.onSnapshot((res) => {
const todos = [];
res.forEach((todo) => {
todos.push(todo.data());
});
});
Does NOT work - returns results that have all statuses. The where query within the IF block has not been applied
const query = db.collection('todos').where('userId', '==', userId);
if (filter === 'complete') {
query.where('status', '==', 'pending');
}
if (filter === 'complete') {
query.where('status', '==', 'complete');
}
query.onSnapshot((res) => {
const todos = [];
res.forEach((todo) => {
todos.push(todo.data());
});
});
Another example to ensure that the if block itself is not the issue here. An initial query created and a 'where' condition added after it (but before the onSnapshot). In this instance, the userId where clause is applied, however the status where clause is ignored. All status todo's are returned
const query = db.collection('todos').where('userId', '==', userId);
query.where( 'status', '==', 'pending' ); // This 'where' clause is being ignored
query.onSnapshot((res) => {
const todos = [];
res.forEach((todo) => {
todos.push(todo.data());
});
});