I want to bookmark the state of a shiny app in which one input field is dynamically generated via renderUI()
.
All inputs are correctly exported to the generated URL, however, calling the app via the bookmark, always the first entry is selected in the dynamically rendered input field, not the one stored in the URL.
This seems to be due to an incorrect application of the reactive()
function, in which both the independent and the dependent input values are called. The reactive()
function seems to be called twice, once before the dependent input is generated and a second time afterwards. I think that if the app is called via the bookmark, the value for the dependent variable is ignored because the corresponding input field is not yet defined. Instead, always the first entry is selected.
What am I doing wrong, I'm grateful for clarification.
Here is a reproducible example:
library(shiny)
enableBookmarking(store = "url")
ui <- function(request) {
fluidPage(
selectInput("independentInput",
"A or B",
choices = c("A", "B"),
multiple = FALSE),
uiOutput("dependentInput"), # depends on 'independentInput'
textOutput("finalOutput"),
bookmarkButton()
)}
server <- function(input, output) {
# the choices of the secondary select field depend on the "independentInput" selection
output$dependentInput <- renderUI({
if (input$independentInput == "A") {
.label <- "A's child?"
.choices <- c("a1", "a2", "a3") # one set of secondary choices
}
if (input$independentInput == "B") {
.label <- "B's child?"
.choices <- c("b1", "b2", "b3") # an alternative set of secondary choices
}
selectInput("dependentInput",
label = .label,
choices = .choices,
multiple = FALSE)
})
reac <- reactive({
foo <- input$independentInput
bar <- input$dependentInput
print(paste(foo, bar)) # proves that 'reac' initially runs twice, where 'bar' is NULL during the first run.
if (foo == "A") {
return(paste0(foo, "'s child is", bar))
}
if (foo == "B") {
return(paste(foo, "'s child is", bar))
}
})
output$finalOutput <- renderText({
reac()
})
}
shinyApp(ui = ui, server = server)
devtools::install_github("rstudio/shiny")
– Gregor de Cillia