0

I tried to display json data retrieved from database as table in my react component. I am using axios to post and get data from my express server. This is my react component.

import React from "react";
// @material-ui/core components
import withStyles from "@material-ui/core/styles/withStyles";
// core components
import GridItem from "components/Grid/GridItem.jsx";
import GridContainer from "components/Grid/GridContainer.jsx";
import Table from "components/Table/Table.jsx";
import Card from "components/Card/Card.jsx";
import CardHeader from "components/Card/CardHeader.jsx";
import CardBody from "components/Card/CardBody.jsx";

import Button from "components/CustomButtons/Button.jsx";
import CardFooter from "components/Card/CardFooter.jsx";

import axios from "axios";

const styles = {
  cardCategoryWhite: {
    "&,& a,& a:hover,& a:focus": {
      color: "rgba(255,255,255,.62)",
      margin: "0",
      fontSize: "14px",
      marginTop: "0",
      marginBottom: "0"
    },
    "& a,& a:hover,& a:focus": {
      color: "#FFFFFF"
    }
  },
  cardTitleWhite: {
    color: "#FFFFFF",
    marginTop: "0px",
    minHeight: "auto",
    fontWeight: "300",
    fontFamily: "'Roboto', 'Helvetica', 'Arial', sans-serif",
    marginBottom: "3px",
    textDecoration: "none",
    "& small": {
      color: "#777",
      fontSize: "65%",
      fontWeight: "400",
      lineHeight: "1"
    }
  }
};


function createUser() {
  axios.post("http://172.104.189.215:4000/users").then(response => {console.log(response)}).catch(error => {console.log(error.response)});
}

function TableList(props) {


  axios.get("http://172.104.189.215:4000/readUsers").then(json => console.log(json)).catch(err => console.log(err));;


  return (
    <GridContainer>
      <GridItem xs={12} sm={12} md={12}>
        <Button color="primary" onClick={createUser}>Create User</Button>
        <Card>
          <CardHeader color="primary">
            <h4 className={classes.cardTitleWhite}>User List</h4>
            <p className={classes.cardCategoryWhite}>
              {/*Here is a subtitle for this table*/}
            </p>
          </CardHeader>
          <CardBody>
            <Table
              tableHeaderColor="primary"
              tableHead={["Name", "Country", "City", "Salary"]}
              tableData={[
                ["Dakota Rice", "Niger", "Oud-Turnhout", "$36,738"],
                ["Minerva Hooper", "Curaçao", "Sinaai-Waas", "$23,789"],
                ["Sage Rodriguez", "Netherlands", "Baileux", "$56,142"],
                ["Philip Chaney", "Korea, South", "Overland Park", "$38,735"],
                ["Doris Greene", "Malawi", "Feldkirchen in Kärnten", "$63,542"],
                ["Mason Porter", "Chile", "Gloucester", "$78,615"],
                ["LALA", "NOOB", "LOL", "$12345"]
              ]}
            />
          </CardBody>
          <CardFooter>
            <Button color="primary">Update Profile</Button>
          </CardFooter>
        </Card>
      </GridItem>
    </GridContainer>
  );
}

export default withStyles(styles)(TableList);

I successfully retrieve the data from database and display in my console. However, I have no idea how to display it via table. Anyone has good solution on this issue?

2
  • 2
    Please add Table component code to your question Commented Mar 21, 2019 at 9:06
  • 1
    @lankovova you can treat my Table as empty first because I dont know how to pass the json to table. The table code at my question is just hard-code to let me see something on table Commented Mar 22, 2019 at 7:07

3 Answers 3

1

Better approach is to make a separate component for table to show the data that you're receiving from back-end. otherwise, you may do few changes to use the same component in the following way:

        class TableList extends React.Component {
          constructor() {
            super();
            this.state = {
              users: []
            };
          }
          
          function createUser() {
            axios.post("http://172.104.189.215:4000/users").then(response => { 
              console.log(response)}).catch(error => {console.log(error.response)});
            });
          }
          componentDidMount() {
            axios.get("https://pokeapi.co/api/v2/pokemon/ditto/")
              .then(json => {
                this.setState({users: json});
                console.log({json})
              });
              .catch(err => console.log(err));;
          }
          render() {
            const {users} = this.state;
            console.log({users})
            // your table
            return (
              <GridContainer>
                <GridItem xs={12} sm={12} md={12}>
                  <Button color="primary" onClick={createUser}>Create User</Button>
                  <Card>
                    <CardHeader color="primary">
                      <h4 className={classes.cardTitleWhite}>User List</h4>
                      <p className={classes.cardCategoryWhite}>
                        {/*Here is a subtitle for this table*/}
                      </p>
                    </CardHeader>
                    <CardBody>
                      <Table
                        tableHeaderColor="primary"
                        tableHead={["Name", "Country", "City", "Salary"]}
                        tableData={users}
                      />
                    </CardBody>
                    <CardFooter>
                      <Button color="primary">Update Profile</Button>
                    </CardFooter>
                  </Card>
                </GridItem>
              </GridContainer>
            );
          }
        }

        const styles = {
          cardCategoryWhite: {
            "&,& a,& a:hover,& a:focus": {
              color: "rgba(255,255,255,.62)",
              margin: "0",
              fontSize: "14px",
              marginTop: "0",
              marginBottom: "0"
            },
            "& a,& a:hover,& a:focus": {
              color: "#FFFFFF"
            }
          },
          cardTitleWhite: {
            color: "#FFFFFF",
            marginTop: "0px",
            minHeight: "auto",
            fontWeight: "300",
            fontFamily: "'Roboto', 'Helvetica', 'Arial', sans-serif",
            marginBottom: "3px",
            textDecoration: "none",
            "& small": {
              color: "#777",
              fontSize: "65%",
              fontWeight: "400",
              lineHeight: "1"
            }
          }
        };

Sign up to request clarification or add additional context in comments.

4 Comments

Nice work Fahad, this should be accepted answer. The only suggestion I'd make would be to ditch the users const and set tableData from state. E.g. tableData={this.state.users}
@fahadtufail Do you mean change function TableList(props) {} to class TableList extends React.Component ? May I know what is the difference? I am still newbie on this. So at the bottom part, I still export default withStyles(styles)(TableList); ?
@phoon actually function represents stateless components, but in case if you need state in component then stateful(Basic) components are required :)
@fahadtufail other than state, is there any alternative way to convert json to table?
0

when U get data User from API, set it to state users. And Component TableList fill data from state users. So TableList should write as a class Component.

class TableList extends React.Component {
  constructor() {
    super();
    this.state = {
      users: []
    };
  }
  componentDidMount() {
    axios.get("https://pokeapi.co/api/v2/pokemon/ditto/")
      .then(json => {
        this.setState({users: json});
        console.log({json})
      })
      .catch(err => console.log(err));;
  }
  render() {
    const {users} = this.state;
    console.log({users})
    // your table
  }
}

Comments

0

There's a few points to this post. IMHO, it looks like you've hard-coded the data for the table. Does this work? Is your table 'really' expecting an object containing an array, which then contains an array of column data?

As lankovova says, we need to see the table component to understand how the data you're passing into the component would be handled.

You ought to revisit the data structure here as you'd typically expect a single array of JSON objects, not what you have in your example.

As it stands, the API response data will never land in the table as the only thing you do with the data is log it to console or is that your key issue?

2 Comments

currently the table is hardcode because I dont know how to pass the data from json object to table. This is my key issue, you can kindly ignore the hardcoded table part first
Fahad's answer is a good example of an overall component. To answer your specific question, where you assign the hard-coded elements, replace that with the var of interest. E.g. tableData={someVarContainingData}. But this isn't going to work as there are other issues. In fact, Fahad has actually edited your code to provide a comprehensive solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.