0

I am trying to loop out an array from part of the data I got, into my Table header. I use material-UI Table.

The retrieved data looks like this:

0: {baseclass_id: 1, sortOrder: 1, …}
1:
  baseclass: {baseclass_id: 2, name: "10", …}
  baseclass_id: 2
  periodQuantity: Array(3)
    0: {id: 4, period: "may-21", quantity: 44}
    1: {id: 5, period: "jun-21", quantity: 19}
    2: {id: 6, period: "jul-21", quantity: 31}
  sortOrder: 2
  __proto__: Object
2: {baseclass_id: 3, sortOrder: 3, …}
and so on...

I would like to loop out that array, so the headers in my table got the period value as header text and the cell beneath got that quantity value.

Like this, but not with the duplicate value. (This picture has just hard coded values):

enter image description here

This is my code from tableContent.js:

  export const columnsSortiment =  Object.keys('periodquantity').map((key, id)=>{
    return{
      Header: () => (<div style={{ textAlign: "left" }}><b>{'period'}</b></div>),
      id: 'id',  
      accessor: 'quantity',
      Cell: (props) => { return <div style={{ textAlign: "left" }}>{props.cell.value}</div> }
    }
  })

I got an error here that says

Error: Duplicate columns were found with ids: "id, id, id, id, id, id, id, id, id, id" in the columns array above

I think it is because I have 'periodquantity' and not like {periodquantity} but I don't know how to get access to the array. Because when I use {periodquantity} I got :

'periodquantity' is not defined no-undef

I also think it getting wrong in the accessor when it got the same name there.

This is my monthSortiment.js table:


import React, { useState } from "react";
import CssBaseline from '@material-ui/core/CssBaseline'
import MaUTable from '@material-ui/core/Table'
import TableContainer from '@material-ui/core/TableContainer'
import TableBody from '@material-ui/core/TableBody'
import TableCell from '@material-ui/core/TableCell'
import TableHead from '@material-ui/core/TableHead'
import TableRow from '@material-ui/core/TableRow'
import TableFooter from '@material-ui/core/TableRow'
import Tooltip from '@material-ui/core/Tooltip'
import { useTable } from 'react-table'
import { makeStyles } from '@material-ui/core/styles';
import _ from "lodash";
import { Col } from "reactstrap";

function Table({ columns, data, update }) {
  const [selectedID, setSelectedID] = useState(null);
  const classes = useStyles();
  // Use the state and functions returned from useTable to build your UI
  const { getTableProps, getTableBodyProps, headerGroups, rows, prepareRow } = useTable({
    columns,
    data,
    update,
  })

  // Render the UI for your table
  return (
    <TableContainer>
      <Col className="table-size">
        <MaUTable {...getTableProps()} stickyHeader>
          <colgroup>
            <col style={{ width: '5%', textAlign: "right" }} />
            <col style={{ width: '10%', textAlign: "right" }} />
            <col style={{ width: '10%' }} />
            <col style={{ width: '10%' }} />
            <col style={{ width: '10%' }} />
            <col style={{ width: '10%' }} />
            <col style={{ width: '10%' }} />
            <col style={{ width: '10%' }} />
          </colgroup>
          <TableHead>
            {headerGroups.map(headerGroup => (
              <TableRow  {...headerGroup.getHeaderGroupProps()}>
                {headerGroup.headers.map(column => (
                  <TableCell className="year-table-cell" style={{ border: 'none' }} {...column.getHeaderProps()}>
                    {column.render('Header')}
                  </TableCell>
                ))}
              </TableRow>
            ))}
          </TableHead>
          <TableBody {...getTableBodyProps()}>
            {rows.map((row, i) => {
              prepareRow(row)
              return (
                <TableRow {...row.getRowProps()}>
                  {row.cells.map(cell => {
                    return (
                      <TableCell className="year-table-cell" style={{ border: 'none' }} {...cell.getCellProps()}>
                        {cell.render('Cell')}
                      </TableCell>
                    )
                  })}
                </TableRow>
              )
            })}
          </TableBody>
          <TableFooter ></TableFooter>
        </MaUTable>
      </Col>
    </TableContainer>
  )
}
export default Table

And this is my index.js file (the console.log() gives the data I pasted the first up here):

import React, { useState, useEffect, Component } from "react";
import Table from "../../Layout/Shared/TableSelect.js";
import { columns, columnsSortiment, data } from "./tablecontent";
import "some services etc"

const FollowUp = (props: Props) => {
  const [state, setState] = useState([{}]);
  const [dataMonth, setDataMonth] = useState([{}]);
  const tableMonthcolumns = React.useMemo(() => columnsSortiment, []);

function showMonth() {
  fetchMonth(monthStart, monthEnd);
}
const fetchMonth = (event: any) => {
     monthDateTime.start = monthStart;
     monthDateTime.end = monthEnd;
     monthDateTime.filter = filter;

    followUpService
    .GetDataByMonth(monthDateTime).subscribe(
      (response) => handleMonth(response),
      (error) => handleHttpRequestError(error.message));
  };
  const handleMonth = (response: any) => {
    setDataMonth(response)
    console.log(response);
  };

 return (
 ... some code

  <Button onClick={() => showMonth(monthStart, monthEnd, filter)}>Ok</Button>
  <Row>
    <Col id="monthTable" style={{ display: (radioValue == "month" ? "block" : "none") }}>
      <div className="month">
          <FollowUpTable columns={tableMonthcolumns} data={dataMonth} setState={setState} />
      </div>
    </Col>
  </Row>
 ... some code
 );
};
export default FollowUp;

This is my backend model code:

public class GetFollowUpModel
{
   public int Baseclass_id { get; set; }
   public int Sortorder { get; set; }
   public BaseclassModel Baseclass{ get; set; }
   public List<PeriodQuantity> PeriodQuantity { get; set; }
}

And finally my backend service:

public class FollowUpService : BaseService, IFollowUpService
{
  public List<GetFollowUpModel> GetDataByMonth(FollowUpModel followUpData)
  {
     var sumBaseClassQuantity= new List<GetFollowUpModel>();
     int periodQuantityId = 0;
       foreach (var baseclass in baseclasses)
         {
           var periodQuantityList = new List<PeriodQuantity>();
           string month = "";
           foreach (var m in months)
             {
               var periodQuantity = new PeriodQuantity();
               int? sumQuantity = 0;
               var baseclassInData = data.FindAll(x => x.Baseclass_id == baseclass.Baseclass_id).Where(x => x.Month == m);
               foreach (var item in baseclassInData )
               {
                 if (item.Month == m)
                 {
                   sumQuantity += item.sumQuantity ;
                 }
               }
               periodQuantity.Quantity = sumQuantity;
               periodQuantity.Period = m;
               periodQuantityId += 1;
               periodQuantity.id = periodQuantityId;
               periodQuantityList.Add(periodQuantity);
             }
           }
           sumBaseClassQuantity.Add(new GetFollowUpModel
           {
              Baseclass_id = baseclass.Baseclass_id,
              Baseclass = baseclass,
              Sortorder = baseclass.Sortorder,
              PeriodQuantity = periodQuantityList
            });

   return sumBaseClassQuantity;
 }
}

Any ideas? (I hope I have translated all the variables correct from Swedish to English, just for better understanding.)

1 Answer 1

0

You are creating the columns in a wrong way. Following react-table docs id and accessor have to be unique.

Try sometring like this:

const data = [
  { id: 4, period: 'may-21', quantity: 44 },
  { id: 5, period: 'jun-21', quantity: 19 },
  { id: 6, period: 'jul-21', quantity: 31 }
]

export const columns = data.map(d => {
  return {
    Header: () => (
      <div style={{ textAlign: 'left' }}>
        <b>{d.period}</b>
      </div>
    ),
    id: d.id,
    accessor: d.period
  }
})

Then format you data to look like this.

const dataForTable = [{ 'may-21': 44 }, { 'jun-21': 19 }, { 'jul-21': 20 }]
Sign up to request clarification or add additional context in comments.

Comments

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.