Home > Software design >  How to auto increment row id when inserting new row in MUI Data Grid?
How to auto increment row id when inserting new row in MUI Data Grid?

Time:01-24

Im trying to insert rows into my Data Grid component from MUI 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 },
            },
          }}
        />

CodePudding user response:

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

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