I'm creating a to-do application with firebase and typescript. I had this function that returns all the projects a current user has in it's list but when it came to adding information to it, it became hard.
Eventually I find a way but it still wasn't good enough, but certainly not clean and efficient enough. So i used chatbot to optimize it and the response was clean and understandable, but I can't seem to get why I'm getting the error:
Property 'map' does not exist on type 'QuerySnapshot'.
I have no clue what is wrong so maybe one of you can point it out..?
This is the function:
const returnProjects = async (id:string) => {
const array: string[] = [];
const list = document.querySelector<HTMLDivElement>('#projectList');
const projects = await getDocs(collection(db, 'projects'));
const projectsUsersPromise = projects.map(async (doc: any) => ({
users: await getCountFromServer(collection(db, `projects/${doc.id}/users`)),
data: doc.data(),
}));
const projectsUsers = await Promise.all(projectsUsersPromise);
projectsUsers.forEach((project: any) => {
const amountUsers = project.users.data().count;
const { name } = project.data();
const newElement = document.createElement('div');
if (list) list.appendChild(newElement).setAttribute('class', 'projectCard');
newElement.innerHTML = `
<h4>${name}</h4>
<div id='cardBottom'>
<div id='cardUsers'>
<img src='/src/img/user.svg' alt='Users' width='12vw' id='projectUsers'>
<span>${amountUsers}</span>
</div>
<img src='/src/img/info.svg' alt='Further information about this project' width='15vw' id='projectInfo'>
</div>
`;
});
};
CodePudding user response:
As mentioned by @Doug Stevenson according to this Reference QuerySnapshot
does not have any map method If you want to use map method on projects
you can use projects.docs.map
then you will be mapping through the Array<QueryDocumentSnapshot<T>>
which does have map method.
Alternatively you can also use projects.forEach
but then you will lose the accumulation of promises like what you have done in map.
Here’s the updated code:
const returnProjects = async (id: string) => {
const list = document.querySelector<HTMLDivElement>('#projectList');
const projects = await getDocs(collection(db, 'projects'));
const projectsPromises = projects.docs.map(async (doc: any) => {
const users = await getCountFromServer(collection(db, `projects/${doc.id}/users`));
const { name } = doc.data();
return { name, users: users.data().count };
});
const projectsData = await Promise.all(projectsPromises);
projectsData.forEach((project: any) => {
const newElement = document.createElement('div');
if (list) list.appendChild(newElement).setAttribute('class', 'projectCard');
newElement.innerHTML = `
<h4>${project.name}</h4>
<div id='cardBottom'>
<div id='cardUsers'>
<img src='/src/img/user.svg' alt='Users' width='12vw' id='projectUsers'>
<span>${project.users}</span>
</div>
<img src='/src/img/info.svg' alt='Further information about this project' width='15vw' id='projectInfo'>
</div>`;
});
};