I'm working on a Shiny app with editable tables, and I would like to reset the selected page after the user deletes a row to the page the deleted row occupied (in other words, stay on the same page). Here is a small example of what I'm trying to do.
library(shiny)
library(DT)
#>
#> Attaching package: 'DT'
#> The following objects are masked from 'package:shiny':
#>
#> dataTableOutput, renderDataTable
# UI
ui <- fluidPage(
fluidRow(
column(width = 1,
actionButton(inputId = "btn", label = "Delete Selected Row")
),
column(width = 11,
DTOutput(outputId = "cars")
)
)
)
# Server
server <- function(input, output, session) {
# Set the initial data.
data <- reactiveValues(cars = mtcars)
# Display the data.
output$cars <- renderDT(
datatable(data$cars,
filter = "top",
extensions = "Buttons",
selection = "single",
options = list(stateSave = TRUE,
lengthMenu = seq.int(5, 50, 5),
pageLength = 10,
dom = 'Bfltrip',
buttons = I('colvis')),
style = "bootstrap")
)
# Create a proxy for the table.
proxy <- dataTableProxy("cars", deferUntilFlush = FALSE)
# React to the delete button.
observeEvent(input$btn,
{
row <- input$cars_rows_selected
page <- input$cars_state$start / input$cars_state$length + 1 # index of displayed page
data$cars <<- data$cars[-row, ] # delete the row
proxy |> selectPage(page) # select the same page
}
)
}
# Run the application
shinyApp(ui = ui, server = server)
Created on 2025-06-30 with reprex v2.1.1
It might seem a bit odd to use reactiveValues
to hold the lone data table, but in my actual app there are multiple tables stored that way.
To see the problem, select any row in the table from page 2 onward and click the delete button (top left). The correct row is deleted and the table display updates, but it jumps back to page 1. I have confirmed that the page calculation is correct and that the problem occurs whether deferUntilFlush
is set to true (default) or false.
I would really like to fix this without having to use custom JS (which might make future support for the app trickier). Am I doing something wrong, or does selectPage
just not work?