0

My problem is to get the array which is displayed at the console to the view. My method for geting the users documents from collection in firestore:

    var UserData= [];
    componentDidMount() {
        const firestore = getFirestore();
        firestore.collection("users").get().then(data => {

          data.forEach(doc => {

            // console.log( "User",doc.data());
            UserData.push(doc.data());   


          });
          console.log("User:", UserData); 
        });


render() {
  return (

     <div>
        <button onClick={this.onLoad}>Get specific user data</button>
        <button onClick={this.onLoad1}>Get all user data</button>
     </div>

  );
}
}
export default compose()(AdminPanel);

When the page is opened in the console is this: [![enter image description here][1]][1]

So my question is how to make the constructor to get this array of users and visualize them in datatable at the page?

Liverpool
  • 265
  • 7
  • 21

1 Answers1

2

In react .map method is used to iterate through objects and their properties.

return (
   <div>
    <button onClick={this.onLoad}>Get specific user data</button>
    <button onClick={this.onLoad1}>Get all user data</button>
    <table>
        <tbody>
            {UserData.map((user) => {
                           return (
                            <tr key={Math.random()>
                               <td>{user.city}</td>
                               <td>{user.email}</td>
                               <td>{user.firstName}</td>
                               <td>{user.initials}</td>
                               <td>{user.lastName}</td>
                            </tr>
                             )
                           }
                         }
      </tbody>
    </table>
   </div>
  );

It will iterate through all objects in UserData one by one and display their properties in tr item .

Check this React docs page. https://reactjs.org/docs/lists-and-keys.html

Zohaib
  • 967
  • 7
  • 12
  • But how to make it to be in data table with columns?Thank you very much – Liverpool Mar 12 '20 at 19:29
  • It returns me: Expected an assignment or function call and instead saw an expression no-unused-expressions – Liverpool Mar 12 '20 at 20:22
  • try UserData.push(doc); instead of UserData.push(doc.data()); – Zohaib Mar 12 '20 at 20:31
  • it need to have return after map but on the page is nothing – Liverpool Mar 12 '20 at 20:41
  • try now brother. i have again edited code. i added return and () outside of – Zohaib Mar 12 '20 at 20:48
  • In you have to put an attribute of key to make each row unique. . Read this for more knowledge about significance of keys in react. Keys are always used in react when there is a list of elements or array of elements. React uses keys to uniquely identify each row. https://stackoverflow.com/questions/42801343/what-is-the-significance-of-keys-in-reactjs – Zohaib Mar 13 '20 at 04:35