I am building a react application. I have a collection 'posts' from which I need to filter documents if these posts were made by users in a list like [user1, user2 ,...].
I can use the 'in' query and get the documents from the code below. I get a total of 7 posts as expected.
db.collection('posts')
.where('userId', 'in', [...friendList])
.orderBy('timestamp', 'desc')
.onSnapshot((snapshot) => {
console.log('posts for home feed', snapshot);
setPosts(
snapshot.docs.map((doc) => ({
id: doc.id,
post: doc.data(),
}))
);
});
But it can only work if the length of [friendList] is upto 10. I tried to get the snapshots of posts made by each user using promises and iterate over this collected snapshot to get the documents (in posts variable) but I get all posts in the repeated over and over. The code I tried:
export default function Feed({ friendList }) {
// currentUser context
const { currentUser } = useAuth();
// array to save posts from database
const [posts, setPosts] = useState([]);
// function to fetch data from database
useEffect(() => {
getPostsFromFriendList(friendList);
}, []);
async function getPostsFromFriendList(friendList) {
const promises = [];
for (let i = 0; i < friendList.length; i++) {
promises.push(getPosts(friendList[i]));
}
const postsForHomeFeed = await Promise.all(promises);
const array = [];
for (let i = 0; i < postsForHomeFeed.length; i++) {
postsForHomeFeed[i].docs.map((doc) => {
array.push({
id: doc.id,
post: doc.data(),
});
});
}
setPosts(array);
console.log('posts for home feed', postsForHomeFeed);
}
function getPosts(userId) {
return new Promise((resolve, reject) => {
db.collection('posts')
// .orderBy('timestamp', 'desc')
.onSnapshot((snapshot) => {
resolve(snapshot);
});
});
}
The console output trying to print the collected snapshots:console output
The resulting array length of the combined snapshots is 3 as expected(friendList has 3 elements). Each of them is a firestore delegate. But each of these elements have a docs property of array length 26. The total documents in the post collection is 26. Why might this be happening?
I am sorry that I am rambling on and on. And thank you for reading my long question. I am grateful for any help I can get.
The reason for that is that you get all posts in getPosts. You would need to add the "where in" filter tehre to make it work:
function getPosts(userId) {
return new Promise((resolve, reject) => {
db.collection('posts')
.where('userId', 'in', [userId])
// .orderBy('timestamp', 'desc')
.onSnapshot((snapshot) => {
resolve(snapshot);
});
});
}