'ReactJS: map json and return to Table

I need to put the fetched data in a Table (it's a very simple CRUD)

I've tested putting the map() function outside of the Management() function but it doesn't work.

Here is my code :

let allUsers = [];

function Management() {
  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) {
          const querySnap = await getDocs(
            collection(db, `users/${item.id}/general`)
          );
          allUsers.push(
            querySnap._snapshot.docChanges[0].doc.data.value.mapValue.fields
              .data.mapValue.fields
          );
        }
      } catch (err) {
        console.log(err);
      }
    };
    fetchData();
  }, []);

  return (
    <Table>
      <thead>
        <tr>
          <th>#</th>
          <th>Nom</th>
          <th>Prénom</th>
          <th>Email</th>
        </tr>
      </thead>
      <tbody>
        {allUsers.map((user) => {
          return (
            <tr>
              <th scope="row">1</th>
              <td>{user.email.stringValue}</td>
              <td>a</td>
              <td>@mdo</td>
            </tr>
          );
        })}
      </tbody>
    </Table>
  );
}

export default Management;

The problem occurs on the allUsers.map() function.

It seems that it returns an empty array



Solution 1:[1]

You are not changing the state of the component Since you are using a functional component, please use useState.

function Management() {
const [allUsers , setAllUsers] = React.useState<any>([]);
useEffect(() => {
const fetchData = async () => {
let allUsersData=[];
  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) {
      const querySnap = await getDocs(
        collection(db, `users/${item.id}/general`)
      );
      allUsersData.push(
        querySnap._snapshot.docChanges[0].doc.data.value.mapValue.fields
          .data.mapValue.fields
      );
setAllUsers(allUsers);
    }
  } catch (err) {
    console.log(err);
  }
};
fetchData();
}, []);  return (
<Table>
  <thead>
    <tr>
      <th>#</th>
      <th>Nom</th>
      <th>Prénom</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    {allUsers.map((user) => {
      return (
        <tr>
          <th scope="row">1</th>
          <td>{user.email.stringValue}</td>
          <td>a</td>
          <td>@mdo</td>
        </tr>
      );
    })}
  </tbody>
</Table>  );
}
export default Management;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Karthik