Reset a DT table to the original sort order

Viewed 475

I have a shiny app with a DT table that allows column sorting. When the data is replaced, I want to also remove any column sorting the user may have clicked. However, when the data is replaced, it is automatically sorted based on the sorting specified in the table. I don't see any option to reset the sorting as part of the replaceData function or as a standalone proxy function. Is it possible to do this without re-rendering the table?

library(DT)
library(shiny)

ui <- fluidPage(
    DTOutput(outputId = "table"),
    actionButton(inputId = "replace", label = "Replace Data")
)

server <- function(input, output) {
    
    output$table <- renderDT({
        datatable(data = data.frame(COL_1 = c(1, 3, 2)), rownames = FALSE)
    })
    
    observeEvent(input$replace, {
        
        data <- data.frame(COL_1 = c(4, 6, 5))
        
        replaceData(proxy = dataTableProxy(outputId = "table"),
                    data = data,
                    rownames = FALSE)
        
    })
    
}

shinyApp(ui = ui, server = server)
1 Answers

I figured out a javascript solution.

library(DT)
library(shiny)
library(shinyjs)

clearSorting <- function(proxy) {
  runjs(paste0("$('#' + document.getElementById('", proxy$id,"').getElementsByTagName('table')[0].id).dataTable().fnSort([]);"))
}

ui <- fluidPage(
  DTOutput(outputId = "table"),
  actionButton(inputId = "replace", label = "Replace Data"),
  useShinyjs()
)

server <- function(input, output) {
  
  output$table <- renderDT({
    datatable(data = data.frame(COL_1 = c(1, 3, 2)), rownames = FALSE)
  })
  
  observeEvent(input$replace, {
    
    data <- data.frame(COL_1 = c(4, 6, 5))
    
    clearSorting(proxy = dataTableProxy(outputId = "table"))
    
    replaceData(proxy = dataTableProxy(outputId = "table"),
                data = data,
                rownames = FALSE)
    
  })
  
}

shinyApp(ui = ui, server = server)
Related