how to save / restore grid state when im changing content of dataSource

i have those 2 functions from documentation:

// Save grid state to local storage

  const saveGridState = () => {

    console.log('Saving grid state');

    const persistData = (gridRef.current as GridComponent).getPersistData(); // Grid persistData

    const selectedReg = `grid_${selectedRegister

      .replace(/\s+/g, '_')

      .toLowerCase()}`;

    window.localStorage.setItem(selectedReg, persistData);

  };


  // Restore grid state from local storage

  const restoreGridState = () => {

    console.log('Restoring grid state');

    const selectedReg = `grid_${selectedRegister

      .replace(/\s+/g, '_')

      .toLowerCase()}`;

    console.log('selectedReg: ', selectedReg);

    const value = window.localStorage.getItem(selectedReg); //"gridOrders" is component name + component id.

    if (value) {

      const state: GridComponent = JSON.parse(value);

      if (state) {

        gridRef.current?.setProperties(state);

      } else {

        console.warn('No state found in local storage');

      }

    } else {

      console.warn('No state found in local storage');

    }

  };

how can i save grid state before i change dataSource and before new grid Table with new dataSource are initialized


1 Reply

PS Pavithra Subramaniyam Syncfusion Team March 31, 2025 12:10 PM UTC

Hi Darius Kumza,


To ensure that the grid state is saved before changing the dataSource, you can add your function where you update the dataSource to first save the grid state and then update the data. Please refer to the below code example.


const updateGridDataSource = (newData: any[]) => {

  // Save the grid state before changing dataSource

  saveGridState();

 

  // Wait for state to save before updating dataSource

  setTimeout(() => {

    console.log('Updating dataSource');

    gridRef.current.dataSource = newData;

  }, 100); // Small delay to ensure persistence

};


You can save the grid state before the grid is initialized inside the load event of Grid component.


function load() {

    var grid =document.getElementsByClassName('e-grid')[0].ej2_instances[0];   

 

    const persistData = grid.getPersistData(); // Grid persistData

 

    const selectedReg = `grid_${selectedRegister

 

      .replace(/\s+/g, '_')

 

      .toLowerCase()}`;

 

    window.localStorage.setItem(selectedReg, persistData);

  }

 


Regards,

Pavithra S


Loader.
Up arrow icon