Peter Andersson
Peter Andersson

Reputation: 2047

Ag-Grid isnt redrawn when using a custom sort

I am using AG-GRID in React (works great otherwise) and I have a column definition that looks like this:

{
    headerName: "Firm",
    sortable: true,
    sort: "asc",
    sortingOrder: ["asc", "desc"],
    headerTooltip: "Firm",
    field: "firm",
    cellStyle: { "text-align": "left" },
    comparator: (valueA, valueB, nodeA, nodeB, isInverted) => {
        let retval;
        if (isInverted) {
            retval = valueB.localeCompare(valueA);
        } else {
            retval = valueA.localeCompare(valueB);
        }
        return retval;
    }
}

The reason I added a custom comparator is that the default one is case-sensitive so "Abc" is sorted after "xyz".

Since my first try didnt work, I tried to simplify the example to the above code, which should as I understand it work exactly as the default sort.

But the problem is that nothing happens in the grid.

Note that the sorting arrows are shown in the header when I click it. I only have one sort-capable column and this is the one. And I can verify it is called, I log the values to the console and both the values and the return value are OK. The inverse flag is correctly set on every other click on the header.

But the grid isnt updated??? Why?

If I remove the comparator code, everything works as before. With case-sensitive compare.

Do I need to do something more when using a custom comparator?

Feels like I'm missing something simple.

--- EDIT ---

If I for some unknown reason would return random values from the sort function, like this

comparator: (valueA, valueB, n1, n2, inverse) => {
    if (valueA === valueB) return 0;
    if (Math.random() > 0.5) {
        return valueA < valueB ? -1 : 1;
    } else {
        return valueA > valueB ? -1 : 1;
    }
}

Then the grid IS updated.... random ordering of rows of course but at least something happens. When I have the "right" sort function, nothing happens....

Can anyone explain this weird behaviour?

Upvotes: 1

Views: 906

Answers (1)

Peter Andersson
Peter Andersson

Reputation: 2047

Found the answer after writing a simple test app and testing every possibility.

Apparently you should ignore the inverse argument, and sort "normally" whatever value the inverse parameter has. So the correct code should be:

comparator: (valueA, valueB, n1, n2, inverse) => {
  if (valueA === valueB) return 0;
  return valueA < valueB ? -1 : 1;
}

or as in my case with Strings:

comparator: (valA, valB, n1, n2, inverse) => {
  return valA.localeCompare(valB);
}

The Grid seems to reverse this sorting internally whenever the sortOrder changes from "asc" to "desc"

Upvotes: 3

Related Questions