2

I'm trying to get sort model from ag-grid-react component using getSortModel() but I'm getting getSortModel is not a function

my code

 onSortChanged={useCallback(e => console.log(e.api.getSortModel(), 'im from sort'))}

"@ag-grid-community/react": "27.3.0", "@ag-grid-enterprise/all-modules": "27.3.0",

KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133

2 Answers2

3

After spend some time found params.api.getSortModel() is deprecated after version 24.0.0.

Using Column state for get Sort model and set Sort model in the following way

getSortModel:

   const onSortChanged = useCallback(() => {
        const value = gridParams.columnApi.getColumnState().find(s => s.sort != null)
        if (value) {
            setSortModel([ value ])
        } else {
            setSortModel([])
        }
    }, [ gridParams, setSortModel ])

setSortModel:

useEffect(() => {
    if (sortModel.length > 0) {
       const curretSortModel = gridParams.columnApi.getColumnState()
       const mergeSortModel = curretSortModel.map(o1 => sortModel.find(o2 => o2.colId === o1.colId) || o1)
       gridParams.columnApi.setColumnState(mergeSortModel)
     }
}, [gridParams, sortModel]
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133
0

As per this plunkr, you can retrieve and apply sort with the following example: https://plnkr.co/edit/?open=index.jsx&preview

 const sortByAthleteDesc = useCallback(() => {
    gridRef.current.columnApi.applyColumnState({
      state: [{ colId: 'athlete', sort: 'desc' }],
      defaultState: { sort: null },
    });
  }, []);


  const saveSort = useCallback(() => {
    var colState = gridRef.current.columnApi.getColumnState();
    var sortState = colState
      .filter(function (s) {
        return s.sort != null;
      })
      .map(function (s) {
        return { colId: s.colId, sort: s.sort, sortIndex: s.sortIndex };
      });
    savedSort = sortState;
    console.log('saved sort', sortState);
  }, []);