Grid onItemsChange

1 Answer 48 Views
Grid
Sanja Tolo
Top achievements
Rank 1
Iron
Iron
Sanja Tolo asked on 01 Sep 2023, 10:33 AM | edited on 01 Sep 2023, 10:34 AM

Hi,

We have a use case in our project where we need to track changes made for the user to provide the batch edit functionality. So we have data and initialData initialized, data is passed to the grid and in onItemsChange we change only the data, and we never touch the initialData except if the data from the server comes back(we make new API call). 
But the initialData changes also when we change data.

Here is reproduced example that I got from your page and i just added initialData state. Here we can see that everything changes and not just data={data} that was passed to the grid and updated in onItemsChange function.

Demo: Demo from KendoReact examples

Is this the expected behaviour that initialData, data and even sampleproducts change even though i only want to modify data that was passed to grid, and the one modified in onItemsChange function.

Best regards

1 Answer, 1 is accepted

Sort by
0
Konstantin Dikov
Telerik team
answered on 02 Sep 2023, 08:22 AM

Hello Sanja,

The behavior that you are facing is due to the reference of the items. Although that you are using "map" function within the onItemChange event, you are passing the same dataItem, which does not clone it and keeps the references. Here is the correct way to modify the data:

const App = () => {
  const [data, setData] = React.useState<Array<Product>>(allInEdit);
  const [initialData, setInitialData] =
    React.useState<Array<Product>>(allInEdit);

  const itemChange = (e: GridItemChangeEvent) => {
    let newData = data.map((item: Product) => {
      if (item.ProductID === e.dataItem.ProductID) {
        return {
          ...item,
          [e.field || '']: e.value,
        };
      }
      return item;
    });
    setData(newData);
  };

Another option would be to simple set the "sampleProducts" to the initial state:

import { sampleProducts } from './sample-products';

const allInEdit: Array<Product> = sampleProducts.map((item) => {
  return { ...item, inEdit: true };
});

const App = () => {
  const [data, setData] = React.useState<Array<Product>>(allInEdit);
  const [initialData, setInitialData] =
    React.useState<Array<Product>>(sampleProducts );

Hope this helps.

 

Regards,
Konstantin Dikov
Progress Telerik

Stay tuned by visiting our public roadmap and feedback portal pages! Or perhaps, if you are new to our Kendo family, check out our getting started resources!

Tags
Grid
Asked by
Sanja Tolo
Top achievements
Rank 1
Iron
Iron
Answers by
Konstantin Dikov
Telerik team
Share this question
or