Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React.js, how to properly use the map() function to display data?

I’m tying to display user data in one of my pages in an electron app. I get the data from firebase/firestore and then put it in an array, then, I want to display that data in a table but I can’t manage to display the data on the page.

Here is my code :

function Home() {
  const [allUsers] = useState([]);
  useEffect(() => {
    const fetchData = async () => {
      try {
        const querySnapshot = await getDocs(collection(db, 'users'));
        let allDocs = [];
        querySnapshot.forEach((doc) => {
          allDocs.push({ ...doc.data(), id: doc.id });
        });
        for (const item of allDocs) {
          allUsers.push(item);
        }
      } catch (err) {
        console.log(err);
      }
      console.log(allUsers)
    };
    fetchData();
  }, []);


  return <div className="home">
    {Object.keys(allUsers).map((keyName) => (         
    <p>{allUsers[keyName].firstname}</p>
    ))}
  </div>;
}

Here is how the data looks like :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Data

>Solution :

You should be using a state setter to update allUsers. You are mutating data (anti React pattern). Try doing so (I added comments in the code):

function Home() {
  const [allUsers, setAllUsers] = useState([]); // line I changed
  useEffect(() => {
    const fechedUsers =[];  // line I added
    const fetchData = async () => {
      try {
        const querySnapshot = await getDocs(collection(db, 'users'));
        let allDocs = [];
        querySnapshot.forEach((doc) => {
          allDocs.push({ ...doc.data(), id: doc.id });
        });
        for (const item of allDocs) {
          fechedUsers.push(item);
        }
      } catch (err) {
        console.log(err);
      }
      setAllUsers(fechedUsers) // line I added
    
    };
    fetchData();
  }, []);

  // lines I changed
  return <div className="home">
    {allUsers.map(user => <p>{user.firstname}</p>)}
  </div>;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading