'How to add/subtract dates on button click?

On button click, I am trying to add/subtract the given date.
Making use of setDate and getTime I managed to get the correct date.

const subtract = (params) => {
    const subtracted = new Date(
      params.setTime(new Date(params).getTime() - (3600 / 60) * 60000)
    ).toLocaleTimeString("en-UK", options);
    console.log("subtracted", subtracted);
    return subtracted;
  };

If you check in the `dev tools/console` the value called `subtracted` you will see that subtraction works correct. But on the table it is still the old value, it doesn't update. Here is the code and the [sandbox demo link][1]
https://codesandbox.io/s/aggridsubtract-time-vqh95f
import React from "react";
import { AgGridReact } from "ag-grid-react";
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine.css";

const options = {
  hour: "2-digit",
  minute: "2-digit",
  hour12: false
};
function App() {
  const [gridApi, setGridApi] = React.useState(null);
  const [gridColumnApi, setGridColumnApi] = React.useState(null);

  const onGridReady = (params) => {
    setGridApi(params.api);
    setGridColumnApi(params.columnApi);
  };

  const subtract = (params) => {
    const subtracted = new Date(
      params.setTime(new Date(params).getTime() - (3600 / 60) * 60000)
    ).toLocaleTimeString("en-UK", options);
    console.log("subtracted", subtracted);
    return subtracted;
  };

  var rowData = [
    {
      id: 1,
      name: "John",
      time: new Date()
    },
    {
      id: 2,
      name: "David",
      time: new Date()
    },
    {
      id: 3,
      name: "Dan",
      time: new Date()
    }
  ];

  const defaultColDef = {
    flex: 1,
    editable: true
  };

  const columnDefs = [
    {
      headerName: "Name",
      field: "name"
    },
    {
      headerName: "time",
      field: "time",
      cellRenderer: ({ value }) => (
        <div>
          <button onClick={() => subtract(value)}>-</button>
          {value.toLocaleTimeString("en-UK", options)}
          <button>+</button>
        </div>
      )
    }
  ];

  return (
    <div>
      <h1 align="center">React-App</h1>
      <div>
        <div className="ag-theme-alpine" style={{ height: "700px" }}>
          <AgGridReact
            columnDefs={columnDefs}
            rowData={rowData}
            defaultColDef={defaultColDef}
            onGridReady={onGridReady}
          ></AgGridReact>
        </div>
      </div>
    </div>
  );
}

export default App;

Any help will be appreciated



Solution 1:[1]

Created a child component to manage date state of each object in rowData array. I have updated your code. Use it as an example to improve your code. (please refer the link here)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Kavindu Vindika