React.JS: Issue With Creating Table Headers Programatically

28 views Asked by At

I'm pretty new to React and am having issues rendering the headings of a table programatically: Basically I want each heading to be from an array. I am creating the array in the constructor, and referencing it later. For now I just want to get headings to worker, but later I would like to set each cell with a value from an array. What I have so far is this:

import React from "react";
import firebase from "../firestore";

const db = firebase.firestore();
const docRef = db.collection("tournaments").doc("Siege");


class Table extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
              matches: [],
              headers:[],
        };
    }

    componentDidMount() {
        let headers =["Time"];
        let matches = docRef.collection("Matches").get().then(querySnapshot => {
            matches = querySnapshot.docs.map(doc => doc.data());
            this.setState( {matches});
            docRef.get().then(snapshot=> {
                var noPitches=snapshot.data().numberPitches;
                for (let i=1; i<noPitches; i++){
                    headers.push("Pitch " + i);
                }
            });
            this.setState({headers});
        });
    }





    render() {

        return (

            <div>
                <table id='mytable'>
                    <thead>
                    <tr>
                        { this.state.headers.map((header,index) =>
                        <th key={index}>{header} </th>
                        )}
                    </tr>
                    </thead>
                </table>
            </div>
        )
    }
}
export default Table;


When The table is rendered, I can only see the first heading, time. When outputting the headings array to the console I can see, it actually does the log three times. The first two times, both headers and this.state.headers are empty, the third time it logs the right value. I'm really confused as to what is happening and any help would be appreciated.

Web Console Table Ouput

0

There are 0 answers