We are currently developing an R Shiny app for our business at Lonsec. The UI of this app and the corresponding observers (eventObservers) is dynamically generated when the user selects from the choice of menu options. This UI contains sliderInput controls that trigger observers (pay attention to the console) upon the app initialisation (that should not happen, and it does not happen with the controls that do not require mandatory value, e.g. actionButton or textInput, etc).
Has everyone come across of thi problem and found a robust workaround for this issue (related to observers triggering during the initialisation as well as their destruction)?
Thank you,
Sergei
library(shiny)
ui = basicPage(
fluidRow(actionButton(inputId = "add_buttons", label = "Add 5 Sliders")),
uiOutput("more_buttons") # this is where the dynamically added buttons will go.
)
server = function(input, output, session)
{
rvs <- reactiveValues(observers = list(), buttons = list())
observeEvent(input$add_buttons,{
l = length(rvs$buttons) + 1
for(i in l:(l+4)) {
rvs$buttons[[i]] = sliderInput(
inputId = paste0("button", i),
label = paste0("Slider ", i),
min = 1,
max = 5,
step = 1,
value = i
)
}
#rvs$observers <-
lapply(
l:(l+4),
function(i) {
observeEvent(input[[paste0("button",i)]],{
if(!identical(rvs$observers[i], input[[paste0("button",i)]])) {
print(sprintf("You used the slider number %d",i))} else {
rvs$observers[i] <- input[[paste0("button",i)]]}
},ignoreInit=TRUE)
}
)
}
)
output$more_buttons <- renderUI({
do.call(fluidRow, rvs$buttons) # Add the dynamic buttons into a single fluidRow
})
}
shinyApp(ui = ui, server = server)
shinyApp(ui, server)