writer_typer
writer_typer

Reputation: 798

How to preserve order of selectInput variables on restore?

I noticed that the selectinput options are not ordered the right way when restoring the app from a bookmark. I found that this is a known issue. However, I'm trying to find a way to workaround this. For example, in the screenshot below I entered in order 8, 7, 6, 5, 4, 3, 2, and 1. But on restoring it, the order defaulted to 1, 2, 3, 4, 5, 6, 7, 8.

Screenshot

enter image description here

Code

library(shiny)

ui <- function(request) {
  fluidPage(
    verticalLayout( 
      div(style = "height: 20vh"), 
      div(style = "height: 40vh;", 
          htmlOutput("text", style = "text-align: center;")
          ),
      div(style = "display: flex; justify-content: center;",
          div(style = "display: inline-block; vertical-align: top;",
              selectInput("vars",
                  "Select variables",
                  multiple = TRUE,
                  choices = c(1, 2, 3, 4, 5, 6, 7, 8)),
              bookmarkButton())
      )))
}

server <- function(input, output) {
 
    output$text <- renderText({
      paste0("<p>", input$vars, "</p>")
    })
}

shinyApp(ui, server, enableBookmarking = "url")

Upvotes: 1

Views: 116

Answers (1)

r2evans
r2evans

Reputation: 160607

If you read Advanced bookmarking, it hints at the ability to override the normal behavior by using onRestored. Two changes: add session to your server component, and add an onRestored() block.

library(shiny)
ui <- function(request) {
  fluidPage(
    verticalLayout(
      div(style = "height: 20vh"),
      div(style = "height: 40vh;",
          htmlOutput("text", style = "text-align: center;")
          ),
      div(style = "display: flex; justify-content: center;",
          div(style = "display: inline-block; vertical-align: top;",
              selectInput("vars",
                  "Select variables",
                  multiple = TRUE,
                  choices = c(1, 2, 3, 4, 5, 6, 7, 8)),
              bookmarkButton())
      )))
}

server <- function(input, output, session) {
  onRestored(function(state) {
    updateSelectInput(session, "vars", selected = state$input$vars)
  })
  output$text <- renderText({
    paste0("<p>", input$vars, "</p>")
  })
}

shinyApp(ui, server, enableBookmarking = "url")

(I also tested this with onRestore (no trailing d), and it worked there as well. The documentation clearly suggests using onRestored for calling update* functions, so I'll go with that without knowing precisely why.)

Upvotes: 1

Related Questions