Search code examples
reactjsmaterial-uidatagridintervals

Is there any way to put a timer into a datagrid in react mui


Im' trying to put a timer. The row gets the timestamp from the store and and makes a subtraction. Data is dynamically fill.

I'm using React MUI (Datagrid) and I can't figure it out.

I can see the correct value on console but the datagrid shows nothing.

What I got:

function loopT(params) {
  let id = params.row.id;
  let impact = params.row.impact; => Timestamp of the impact
  clearTimeout(id);
  id = setInterval(function () {
    const currentDate = new Date();
    let seconds = Math.floor(currentDate.getTime() / 1000) - impact;

    console.log("The time was: ",seconds)

    return seconds;
  }, 1000);
}

const columns = [
  {
    field: 'id',
    headerName: 'id',
    width: 100,
  },
  {
    field: 'lastname',
    headerName: 'lastname',
    width: 100,
  },
  {
    field: 'name',
    headerName: 'name',
    width: 100,
  },
  {
    field: 'impact',
    headerName: 'impact',
    sortable: false,
    width: 100,
    valueGetter: loopT,
  },
];

export default function PanelMonitor() {
  const [realtime, setRealtime] = useState([]);
  const opera_realtime = useSelector(operaRealtime)

  useEffect(() => {
    setRealtime(opera_realtime)
  }, [opera_realtime]);

  return (
    <div style={{ height: 400, width: '100%' }}>
        <DataGrid
            rows={realtime}
            columns={columns}
            rowHeight={38}
            disableSelectionOnClick
        />
    </div>
  );
}

Mi console:

The time was:  13907
The time was:  13908
The time was:  13909
The time was:  13910
The time was:  13911

The result:

id lastname name impact
1 Doe John

No error.

Thanks in advance.


Solution

  • Use the renderCell method

    {
        field: 'impact',
        headerName: 'impact',
        sortable: false,
        width: 100,
        renderCell: (params) => {
         let timer = loopT(params.row) // you can console params to see what you want to send in this function
         return (<p>{timer}</p>);
      },