Home > Net >  How do I show the number of projects each of my members have? FIREBASE REACT
How do I show the number of projects each of my members have? FIREBASE REACT

Time:11-14

This is for my class project, once a user has signed in and clicked on the members page, I wish for them to see the list of all the other members who've signed in previously and show how many projects they each have with a .length of the projects. Everything works except for the projects part and I don't know why. The error i'm getting is this:

error I get

This is the page: page

This is my firebase data: firebase data

Thank you all truly!

This here is my code on the Membres.js file

import { useState, useContext, useEffect } from "react";
import { onSnapshot, collection, addDoc } from 'firebase/firestore';
import { db } from '../../config/firebase';
import { authContexte } from "../../Contexte/authContexte";
import { Link } from "react-router-dom";

const Membres = () =>{
    const ctx = useContext(authContexte);
    const [membres, setMembres] = useState([]);
    
    useEffect(() => {
        const unsub = onSnapshot(collection(db, 'membres'), (snapshot) => {
            setMembres(snapshot.docs.map(doc => {
                return {
                    ...doc.data(),
                    id: doc.id
                };
            }));
        });
        return unsub;
    }, []);
 return(
    <ul className="list-group">
        {membres.map((membre)=>(
            <li className="list-group-item d-flex justify-content-between align-items-center" key={membre.nom   membre.email}>
                {membre.nom} <p>{membre.email}</p>
                <span className="badges">{membre.projets.length}</span> //Need this to work
                {console.log(membre.projets)}
            </li>
        ))}
    </ul>
 );
};
export default Membres;

CodePudding user response:

Try this,

  const Membres = () =>{
    const ctx = useContext(authContexte);
    const [membres, setMembres] = useState([]);
    
    useEffect(() => {
        const unsub = onSnapshot(collection(db, 'membres'), (snapshot) => {
            setMembres(snapshot.docs.map(doc => {
                return {
                    ...doc.data(),
                    id: doc.id
                };
            }));
        });
        return unsub;
    }, []);
 return(
    <ul className="list-group">
        {membres.map((membre)=>(
            <li className="list-group-item d-flex justify-content-between align-items-center" key={membre.nom   membre.email}>
                {membre.nom} <p>{membre.email}</p>
                <span className="badges">{membre.projets ? membre.projets.length : '0'}</span> //Need this to work
            </li>
        ))}
    </ul>
 );
};
export default Membres;

CodePudding user response:

Your projects is a map field, not an array, and a map doesn't have a length.

You can get the keys of the map into an array and use the length of that with:

Object.keys(membre.projets).length
  • Related