Fluxy
Fluxy

Reputation: 2978

How to display dynamic data in Material-UI table?

I have API that returns some tabular data. I need to display these data in a Table. It's not clear to me how to achieve this goal.

Let's assume that I want to display the fields id and name stored in groups. How can I show them in the Material-UI Table?

Please see my current code below. It does not throw any error. But neither is shows a Table with the data.

import '../../App.css';
import React, { useEffect } from 'react'
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import axios from 'axios'
import config from '../../config/config.json';

const useStyles = makeStyles((theme) => ({
    root: {
        width: '100%',
    },
    heading: {
        fontSize: theme.typography.pxToRem(18),
        fontWeight: theme.typography.fontWeightBold,
    },
    content: {
        fontSize: theme.typography.pxToRem(14),
        fontWeight: theme.typography.fontWeightRegular,
        textAlign: "left",
        marginTop: theme.spacing.unit*3,
        marginLeft: theme.spacing.unit*3,
        marginRight: theme.spacing.unit*3
    },
    table: {
        minWidth: 650,
    },
    tableheader: {
        fontWeight: theme.typography.fontWeightBold,
        color: "#ffffff",
        background: "#3f51b5"
    },
    tableCell: {
        background: "#f50057"
    },
    button: {
        fontSize: "12px",
        minWidth: 100
    },
}));


export function Main() {

    const [groups, setGroup] = React.useState('');

    const classes = useStyles();

    const options = {
        'headers': {
            'Authorization': `Bearer ${localStorage.getItem('accessToken')}`
        }
    }

    useEffect(() => {
        axios.get(config.api.url + '/api/test', options)
            .then( (groups) => {
                this.setState({response: groups})
            })
            .catch( (error) => {
                console.log(error);
            })
    }, [])

    return (
        <div className={classes.root}>

            <Grid container spacing={3}>
                <Grid item xs={12} className={classes.content}>
                    <TableContainer component={Paper}>
                        <Table id="split_table" size="small">
                            <TableHead>
                            </TableHead>
                            <TableBody>
                                {Object.keys(groups).map( (row, index) => (
                                    <TableRow key={index} selected="false">
                                        <TableCell>Test</TableCell>
                                        <TableCell>Test</TableCell>
                                    </TableRow>))}
                            </TableBody>
                        </Table>
                    </TableContainer>

                </Grid>    
            </Grid>
        </div>
    )
} 

Update:

As I mentioned in comments, I followed the recommendations from answers, but I still see an empty table, while I can see a correct value in console.

useEffect(() => {
        axios.get(config.api.url + '/api/test', options)
            .then( (groups) => {
                setGroup(groups.data.subtask)
                console.log(groups.data.subtask);
            })
            .catch( (error) => {
                console.log(error);
            })
    }, [])

    return (
        <div className={classes.root}>

            <Grid container spacing={3}>
                <Grid item xs={12} className={classes.content}>
                    <TableContainer component={Paper}>
                        <Table id="split_table" size="small">
                            <TableHead>
                            </TableHead>
                            <TableBody>
                                    {Object.keys(groups).map( (item, index) => (
                                    <TableRow key={index} selected="false">
                                        <TableCell>{item.user_id}</TableCell>
                                        <TableCell>{item.task_name}</TableCell>
                                    </TableRow>))}
                            </TableBody>
                        </Table>
                    </TableContainer>

                </Grid>    
            </Grid>
        </div>
    )

This is what I see in the browser:

enter image description here

This is an example of data (groups.data.subtask):

enter image description here

Upvotes: 2

Views: 10445

Answers (3)

Kevin Moe Myint Myat
Kevin Moe Myint Myat

Reputation: 2165

I think it's the Object.keys(groups) .

It's not React state, so it will not re-render?

Can you try to make a groupKey state and then useEffect to update the state when groups is updated.

const [groupKey,setGroupKey] = useState([]);

useEffect(() => {
  setGroupKey(Object.keys(groups));
},[groups]);

In the component , use

{groupKey.map((item, index) => (
  <TableRow key={index} selected="false">
    <TableCell>{item.user_id}</TableCell>
    <TableCell>{item.task_name}</TableCell>
  </TableRow>))
}

You get the idea.

Upvotes: 1

AlexAV-dev
AlexAV-dev

Reputation: 1175

I think the problem is that you use this.setState instead of setGroup

useEffect(() => {
    axios.get(config.api.url + '/api/test', options)
        .then( (groups) => {
            setGroup(groups)
        })
        .catch( (error) => {
            console.log(error);
        })
}, [])

Change your map function

{Object.keys(groups).map( (row, index) => (
  <TableRow key={index} selected="false">
    <TableCell>{row._id}</TableCell>
    <TableCell>{row.user_id}</TableCell>
  </TableRow>))}

import '../../App.css';
import React, { useEffect } from 'react'
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Table from '@material-ui/core/Table';
import TableBody from '@material-ui/core/TableBody';
import TableCell from '@material-ui/core/TableCell';
import TableContainer from '@material-ui/core/TableContainer';
import TableHead from '@material-ui/core/TableHead';
import TableRow from '@material-ui/core/TableRow';
import Paper from '@material-ui/core/Paper';
import axios from 'axios'
import config from '../../config/config.json';

const useStyles = makeStyles((theme) => ({
    root: {
        width: '100%',
    },
    heading: {
        fontSize: theme.typography.pxToRem(18),
        fontWeight: theme.typography.fontWeightBold,
    },
    content: {
        fontSize: theme.typography.pxToRem(14),
        fontWeight: theme.typography.fontWeightRegular,
        textAlign: "left",
        marginTop: theme.spacing.unit*3,
        marginLeft: theme.spacing.unit*3,
        marginRight: theme.spacing.unit*3
    },
    table: {
        minWidth: 650,
    },
    tableheader: {
        fontWeight: theme.typography.fontWeightBold,
        color: "#ffffff",
        background: "#3f51b5"
    },
    tableCell: {
        background: "#f50057"
    },
    button: {
        fontSize: "12px",
        minWidth: 100
    },
}));


export function Main() {

    const [groups, setGroup] = React.useState([]);

    const classes = useStyles();

    const options = {
        'headers': {
            'Authorization': `Bearer ${localStorage.getItem('accessToken')}`
        }
    }

useEffect(() => {
        axios.get(config.api.url + '/api/test', options)
            .then( (groups) => {
                setGroup(groups.data.subtask)
                console.log(groups.data.subtask);
            })
            .catch( (error) => {
                console.log(error);
            })
    }, [])

return (
    <div className={classes.root}>

        <Grid container spacing={3}>
            <Grid item xs={12} className={classes.content}>
                <TableContainer component={Paper}>
                    <Table id="split_table" size="small">
                        <TableHead>
                        </TableHead>
                        <TableBody>
                                {Object.keys(groups).map( (item, index) => (
                                <TableRow key={index} selected="false">
                                    <TableCell>{item.user_id}</TableCell>
                                    <TableCell>{item.task_name}</TableCell>
                                </TableRow>))}
                        </TableBody>
                    </Table>
                </TableContainer>

            </Grid>    
        </Grid>
    </div>
)

Upvotes: 2

Kabu
Kabu

Reputation: 61

Something like below should help: enter image description here

Upvotes: 1

Related Questions