reactjsnext.jsmaterial-uimui-x-data-grid

How to auto increment row id when inserting new row in MUI X Data Grid?


Im trying to insert rows into my Data Grid component from MUI X Kit without having to deal with the id that i dont need but needs to be unique.

I have tried incrementing the id number based on rows.length but i get 0 all the time for some reason.

Here is my code:

  const initial_rows: GridRowsProp = [];
const [rows, setRows] = React.useState(initial_rows);

for (let j = 0; j < fetched_data.length; j++) {
            console.log(rows.length);
            const newRow = {
              id: rows.length + 1,
              wallet: fetched_data[j]["payment_address"],
              project: "FluxNodes",
              status: "Active",
              collateral: fetched_data[j]["amount"],
              tier: fetched_data[j]["tier"],
              reliability: "?",
              rewards: "?",
              pending_rewards: "?",
            };
            setRows((prevRows) => [...prevRows, newRow]);
          }

<DataGrid
          rows={rows}
          columns={columns}
          pageSize={25}
          rowsPerPageOptions={[25]}
          editMode="row"
          density="compact"
          disableColumnMenu
          disableSelectionOnClick
          loading={loading}
          initialState={{
            sorting: {
              sortModel: [{ field: "ratio", sort: "desc" }],
            },
          }}
          components={{
            Toolbar: GridToolbar,
            LoadingOverlay: LinearProgress,
          }}
          componentsProps={{
            toolbar: {
              showQuickFilter: true,
              quickFilterProps: { debounceMs: 500 },
            },
          }}
        />

Solution

  • You can add an id when rows are passed as props:

    <DataGrid rows={rows.map((item, index) => ({ id: index + 1, ...item }))} .../>