AG Grid - revert to default sorting if no columns are currently sorted

When my ag-grid is initialized, it sorts the data by a default column indicated by this.options.defaultSortColumn. If a user then sorts by another column and removes the sort (by clicking on the header three times), I want to revert back to the default sort and sort by the default column again. Here's what I have tried:

postSort () {
  if (this.gridApi) {
    let currentSort = this.gridApi.getSortModel()
    console.log(currentSort)
    if (this.options.defaultSortColumn && currentSort && currentSort.length === 0) {
      // reset default sort if no other sort is active
      this.gridApi.setSortModel({
        colId: this.options.defaultSortColumn,
        sort: (this.options.defaultSortDir || 'asc').toLowerCase()
      })
    }
  }
}

However, I keep receiving a Maximum call stack size exceeded error. It seems like the function calls itself repeatedly because it sets the sort and triggers the postSort event before the getSortModel() updates. Am I making a mistake here? Are there alternate methods to restore the default sort when no other column is sorted?

Answer №1

An alternative approach is to revert the gridOptions state back to its initial configuration when setting up the grid.

this.gridColumnApi.resetColumnState();

As outlined in the documentation -

resetColumnState() - Restores the state to match the original column definitions.

Answer №2

To clarify any confusion, it is important to note that the setSortModel function should be passed an array as an argument, not an object.

Here is the correct approach using React:

  <AgGridReact onSortChanged={e => {
     if (!e.api.getSortModel().length) {
       e.api.setSortModel([
         {
          colId: 'columnId',
          sort: 'desc' // 'asc'
         }  
       ])
     }   
   }

Answer №3

In order to achieve the desired outcome, you can utilize the following ag grid event - onSortChanged and verify the length of the current sort.

  1. Initialize a default sort and save it to a variable (e.g. defaultSort) upon loading
  2. Utilize the onSortChanged grid API event to monitor the length of the current sort

    onSortChanged: (e) => { console.log(e.api.getSortModel()) }

  3. If the length is 0, establish the default sort using this.gridApi.setSortModel(defaultSort)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implementing precise search functionality in a table with jquery datatables

Hey there, I'm attempting to implement an exact search feature in jQuery datatables. In my table, I have a column called "status" with values of either "paid" or "unpaid". Currently, when I type "unpaid", it correctly displays only the unpaid record ...

Exploring the world of JavaScript by dynamically retrieving all class functions

Is there a way to retrieve an array of all functions from a given class, including functions inherited from parent classes? For instance: class Foo extends Bar { funcA() {} } class Bar { funcB() {} } const instanceFoo = new Foo(); getClass ...

How to use jQuery to hide list items after a certain threshold

$('li[data-number=4]').after().hide(); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li data-number="0"">1</li> <li data-number="1">2</li> ...

What is the extent to which a scope variable will be accessible within the link function of Angular?

var $directive = angular.module('myApp', []); $directive.directive('myDirective', function(){ return { restrict: 'E', template: '<h4>{{title}}</h4>' compile: function(element, attrs){ ...

Can Socket Communication and Server be Established on the Same Port?

Is there a way to make both the socket and server listen on port 443 without receiving the EADDRINUSE warning? I'd like to have them both running on the same port. ...

Utilizing the componentDidUpdate method to update the state within the component

I have a scenario where two components are enclosed in a container. One component is retrieving the Id of a publication, while the other is fetching the issue date related to that specific publicationId. When I retrieve an Id, let’s say 100, it successf ...

What are the steps for encountering a duplicate property error in TypeScript?

I'm currently working with typescript version 4.9.5 and I am interested in using an enum as keys for an object. Here is an example: enum TestEnum { value1 = 'value1', value2 = 'value2', } const variable: {[key in TestEnum]: nu ...

Looping over a JavaScript object to extract text content similar to Python's requests.text

We are currently in the process of transitioning code from a Python web scraper to a Node.js web scraper that will interact with the Pastebin API. The response we receive when scraping is in the form of a JavaScript object as shown below: [ { scrape ...

When inside a function declaration, io.socket is not defined, but it is defined outside of

Trying to utilize io.socket for a POST call to a controller action is presenting some unexpected behavior. Interestingly, when using io.socket.someMethod() within script tags as shown, it works smoothly: <script> io.socket.post('/visualization/ ...

Using JavaScript to modify the -webkit-animation-play-state

Hello, I'm currently facing a challenge in changing my css3 -webkit-animation-play-state property from paused to running upon clicking on another div. Does anyone have any suggestions on how I can achieve this? I believe JavaScript might be the way to ...

Guide to adding a marker in Vue2-Leaflet while ensuring the popup is initially open

Is there a way to set the pop up as initially open when adding a marker dynamically? <v-map> <v-marker v-for="item in markers" :key="item.id" :lat-lng="item.latlng"> <v-popup :content="item.content"></v-popup> </v-marker ...

Executing a function within JSX to dismiss a modal in NextJS

I am currently utilizing the Tanstack React Query library to perform a POST request from a Modal that includes a form: const addDay = (day: TDay) => { const apiURL = process.env.NEXT_PUBLIC_SERVER_URL const queryURL = apiURL + router ...

Include an extra hyperlink in the adaptive menu bar

I have successfully created a responsive Navigation bar. Now, I would like to add an "Account" link on the right side of the navigation. My initial thought was to insert a div into a ul element, but I realize that this may not be W3C compliant. <div c ...

Is it possible to add a class to a child element deep within the component hierarchy while using TransitionGroup/CSSTransition in React?

I currently have a setup like this: Parent Component: <TransitionGroup> { items.map((child, index) => { // do something return ( <CSSTransition key={index} nodeRef={items.nodeRef} timeout={1000} classNames={'item ...

Building a timer using Vue.js and moment.js

I'm currently working on a timer using vue.js and moment.js which specifically focuses on minutes and seconds. My code should technically work as intended, however it's not yielding the desired results: var app = new Vue({ el: '#app&apo ...

How can I initiate an AJAX POST request over HTTPS?

Despite my efforts, I am consistently encountering a 404 error when attempting to make an Ajax POST request. The specific error message reads: "GET 404 (Not Found)." Could this issue be related to the site's use of https? Below is the code snippet t ...

unique color schemes for pie charts with nvd3-angular

I'm attempting to personalize the colors of a pie chart by utilizing the angular-nvd3 extension. I discovered the issue in the plunker example. Although I was able to customize the color of the legend, the chart itself remained unchanged. I would li ...

Using Vuejs to customize the color of disabled drop-down text

I'm trying to achieve the functionality where selecting an item from a dropdown list disables that option. Currently, my code works as expected, but I find the color of the disabled text too light. Is there a way to adjust the color of the disabled te ...

Convert all page links to post requests instead

Currently, I am working on a JavaScript project where my objective is to transform all links on the page into forms. This will enable the requests to be sent using the POST method rather than the GET method. The code I have implemented so far is as follow ...

Counting up in ASP.NET using Javascript

I have been searching for a solution to this online, but haven't had any luck yet. I am in need of a simple JavaScript code (HH:MM:SS) that counts seconds upwards. My web application is ASP.NET with C#. I would like this count to start upon page load. ...