Home > Net >  react did not render all rows and just rendered one object and reapeated
react did not render all rows and just rendered one object and reapeated

Time:11-10

it should populate all rows to the table (the rows are from from the api is an array of objects) currently the issue is only render that last object of the array and I have no idea why it keeps on repeating , as you can see on the screenshot it only loads 1 object and then repeats that is why all the rows have the same value.

By the way the rows or the data from the api is an array of objects /

Maybe someone has an idea on how we can address this issue. Thanks.

enter image description here

#rows from the api result from the console log this is the rows that is been feed to the grid enter image description here

#react code

export const StyledDataGrid = styled(DataGrid)`
    .MuiDataGrid-row: nth-of-type(odd) {
      background: #E3E0E0
    }
    .MuiDataGrid-cell {
      border-right: 1px solid #C4C4C4;
    }
    .MuiDataGrid-columnHeader  {
      border-right: 1px solid #C4C4C4;
    }
    .MuiDataGrid-columnSeparator--sideRight {
      display: none
    }
    .MuiDataGrid-columnHeaderTitleContainer {
      justify-content: space-between;
    }
    .MuiDataGrid-iconButtonContainer  {
      visibility: visible;
      width: auto;
    }
`;

const PortfolioPage: FC = () => {
  const router = useRouter();
  const dispatch = useAppDispatch();
  const { isPending, isError, isSuccess, grid, isSaveSuccess } = useAppSelector(
    (state) => state.region
  );
  const [snackbarOpen, setSnackbarOpen] = useState<boolean>(false);

  const [selectedRow, setSelectedRow] = useState<IRegional | null>(null)

  const rows = grid ? grid.items : [];

  console.log('rows' , rows)


  const fetchGridItems = () => {
     const payload: IPageListApiRequestPayload = {
        accountId: 1,
        sortKey: JSON.stringify([]),
        sortOrder: JSON.stringify([]),
        page: 1,
        pageSize: 100,
        searchString: '',
      };
      dispatch(getRegionGrid(payload));
  }
  useEffect(() => {
    // Save success
    if (isSaveSuccess) {
      setSnackbarOpen(true);
      fetchGridItems();
    }
  }, [isSaveSuccess])
  useEffect(() => {
    if (router.isReady) {
      fetchGridItems();
    }
  }, [router.isReady]);

  const renderList = (data: IEmail) => (
    <div style={{display: 'block'}}>
        <div>Full Name: {data.firstName} {data.lastName}</div>
        <div>Email Address: {data.emailAddress}</div>
    </div>
  )

  const columns: GridColDef[] = [
    {
      field: "associateDirectorofConstructionOps",
      headerName: "Associate Director of Construction Ops",
      minWidth: 300,
      flex: 0.16,
      disableColumnMenu: true,
      renderCell: (params: GridRenderCellParams<string>) => (
        <>
           {
             params.row.associateDirectorofConstructionOps ? params.row.associateDirectorofConstructionOps.map((prop: IEmail) => renderList(prop))
              : null
           }
        </>
      ),
    },
  ];
  const fixedColumnLeft: GridColDef[] = [
    {
      field: "regionName",
      headerName: "Region Division",
      flex: 0.08,
      minWidth: 100,
      disableColumnMenu: true,
    },
    {
      field: "subRegionName",
      headerName: "Sub-Region",
      flex: 0.15,
      minWidth: 50,
      disableColumnMenu: true,
    },
    {
      field: "marketName",
      headerName: "Market",
      flex: 0.08,
      minWidth: 50,
      disableColumnMenu: true,
    },
  ];
  const fixedColumnRight: GridColDef[] = [
    {
      field: "action",
      disableColumnMenu: true,
      sortable: false,
      renderHeader: () => <></>,
      renderCell: (params: GridRenderCellParams<string>) => (
        <div
          style={{
            color: "rgb(110 110 110)",
            display: "flex",
            justifyContent: "space-between",
          }}
        >
          <EditIcon onClick={() => handleClickOpen(params)} />
        </div>
      ),
    },
  ];
  const [open, setOpen] = React.useState<boolean>(false);
  const handleClickOpen = (data: any) => {
    setSelectedRow(data.row);
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };
  return (
    <Box sx={{ height: "100vh", background: "#EEEAEA" }}>
      <Snackbar
        open={snackbarOpen}
        autoHideDuration={3000}
        onClose={() => setSnackbarOpen(false)}>
        <Alert onClose={() => setSnackbarOpen(false)} severity="success" sx={{ width: '100%' }}>
              Successfully saved!
        </Alert>
      </Snackbar>
      <EditProperties open={open} handleClose={handleClose} selectedRow={selectedRow} />
      <DashboardWrapper seoProps={{
        title: "PIM | Regions",
        }}
        title="Properties"
        mainClass="properties-page">
        {isError ? <div>Error Loading Regions!</div> : ""}
        {isPending ? <>Loading Regions...</> : ""}
        {isSuccess ? (
        <>
            <div
              style={{
                display: "flex",
                justifyContent: "space-between",
                width: "636px",
                height: "56px",
                background: "rgba(37, 36, 41, 0.9)",
                padding: "8px 16px 8px 8px",
                borderBottomRightRadius: "30px",
              }}
            >
              <Input
                size="small"
                style={{
                  width: "461px",
                  height: "40px",
                  background: "#FFFFFF",
                  borderRadius: "4px",
                  outline: "none",
                }}
                placeholder="Search  by typing property name or address"
                startAdornment={
                  <InputAdornment position="start">
                    <SearchIcon />
                  </InputAdornment>
                }
              />
              <Button
                variant="contained"
                style={{ textTransform: "capitalize" }}
              >
                Search
              </Button>
              <div
                style={{
                  display: "flex",
                  color: "#FFFFFF",
                  flexDirection: "column",
                  justifyContent: "space-between",
                  alignItems: "center",
                  marginRight: "10px",
                }}
              >
                <TuneIcon style={{ fontSize: "32px" }} />
                <span style={{ fontSize: "10px", marginTop: "-5px" }}>
                  Filters
                </span>
              </div>
            </div>
            <TableContainer component={Paper} style={{ marginTop: "24px" }}>
              <div
                style={{
                  borderBottom: "1px solid #C4C4C4",
                  padding: "16px",
                  display: "flex",
                  justifyContent: "space-between",
                  background: "#FFFFFF",
                  height: "72px",
                }}
              >
                <label
                  style={{
                    fontWeight: "600",
                    fontSize: "24px",
                    color: "#252429",
                    alignSelf: "center",
                  }}
                >
                  {" "}
                  Regions{" "}
                </label>
                <div
                  style={{
                    alignSelf: "center",
                    color: "#C4C4C4",
                    display: "flex",
                    fontSize: "16px",
                  }}
                >
                  <IosShareIcon style={{ marginRight: "14px" }} />
                  Export
                </div>
              </div>
              {/* Table container */}
              <div style={{position: "relative", display: 'flex', justifyContent: 'space-between'}}>
                  {/* Left table */}
                  <Box
                    sx={{ boxShadow: 5 }}
                    style={{
                      width: "20%",
                   
                      zIndex: 99,
                      overflow: "hidden",
                      background: "#FFFFFF",
                    }}
                  >
                    <StyledDataGrid
                      autoHeight 
                      getRowId={(row) => row.accountId}
                      hideFooterPagination={true}
                      components={{
                        ColumnSortedAscendingIcon: UnfoldMoreIcon,
                        ColumnSortedDescendingIcon: UnfoldMoreIcon,
                      }}
                      rows={rows}
                      columns={fixedColumnLeft}
                      disableSelectionOnClick
                      experimentalFeatures={{ newEditingApi: true }}
                    />
                  </Box>

                  {/* Center table */}
                <div style={{overflow: 'hidden', width: '70%'}}>
                  <div style={{ width: '2000px', margin: 'auto', overflow: "hidden"}} >
                    <StyledDataGrid
                      autoHeight 
                      getRowId={(row) => row.accountId}
                      components={{
                        ColumnSortedAscendingIcon: UnfoldMoreIcon,
                        ColumnSortedDescendingIcon: UnfoldMoreIcon,
                      }}
                      rows={rows}
                      columns={columns}
                      pageSize={100}
                      rowsPerPageOptions={[10, 20, 50, 100]}
                      disableSelectionOnClick
                      experimentalFeatures={{ newEditingApi: true }}
                    />
                  </div>
                </div>

                  {/* Right table */}
                  <Box
                    sx={{ boxShadow: 5 }}
                    style={{
                      width: "10%",
                      zIndex: 99,
                      overflow: "hidden",
                      background: "#FFFFFF",
                    }}
                  >
                    <StyledDataGrid
                      autoHeight 
                      getRowId={(row) => row.accountId}
                      hideFooterPagination={true}
                      components={{
                        ColumnSortedAscendingIcon: UnfoldMoreIcon,
                        ColumnSortedDescendingIcon: UnfoldMoreIcon,
                      }}
                      rows={rows}
                      columns={fixedColumnRight}
                      disableSelectionOnClick
                      experimentalFeatures={{ newEditingApi: true }}
                    />
                  </Box>
              </div>
            </TableContainer>
            {/* <ActionButtonContainer
              btnNameOne="Property"
              btnNameTwo="Properties"
              btnIconOne={<UploadFileIcon />}
              btnIconTwo={<AddIcon />}
            /> */}
          </>
        ) : (
          ""
        )}
      </DashboardWrapper>
    </Box>

CodePudding user response:

Yes because of this

enter image description here

This line is the cause of all these problems

The DataGrid expects a unique key for every row in the table

so it's asking you where it can find that unique key

You're telling it that it can find it inside the accountId prop.

Which is not accurate because it has duplicates

Normally this should be id, but it's null everywhere in your case.

If the data source coming from your API has a property called "id", the MUI DataGrid is automatically going to use it if you didn't set the getRowId prop.

  • Related