Persistent inputs with renderUI and modules

CONTEXT
I'm working on an app that has an input with multiple choices, and those choices can change dynamically (i.e. more choices can be added). Each choice can be selected, which will update the UI based on that selected choice. I have opted to use shiny modules in this case.

QUESTION
This particular question is about persistent inputs within each module, and therefore my minimal reproducible example below fixes the number of choices to two. My question:

Why do I need a reactive trigger to make the input slider persistent?

library(shiny)

`%||%` <- function(x, y) if (is.null(x)) y else x

ui <- fluidPage(
  titlePanel("Persistent Inputs with Modules"),
  sidebarLayout(
    sidebarPanel(
      radioButtons("radio", label = h3("Choices"),
                   choices = list("First" = "first", "Second" = "second"), 
                   selected = "first")
    ),
    mainPanel(
      uiOutput("sliderUI"),
      verbatimTextOutput("firstSlider")
    )
  )
)

server <- function(input, output, session) {
  callModule(module = sliderMod, id = "first", reactive({input$radio}))
  callModule(module = sliderMod, id = "second", reactive({input$radio}))
  
  output$sliderUI <- renderUI({
    req(input$radio)
    sliderModUI(id = input$radio)
  })
  
  output$firstSlider <- renderPrint({
    req(input[["first-slider"]])
    paste("First Slider:", input[["first-slider"]])
  })
}

sliderModUI <- function(id) {
  ns <- NS(id)
  uiOutput(ns("sliderModUI"))
}

sliderMod <- function(input, output, session, newChoice) {
  output$sliderModUI <- renderUI({
    # newChoice()
    sliderInput(inputId = session$ns("slider"), 
                label = "",
                min = 0,
                max = 1,
                value = isolate(input$slider) %||% 1)
  })
}

shinyApp(ui = ui, server = server)

COMMENTS
I pass in the radio input value to the module and use it as the reactive trigger for the output$sliderModUI renderUI bit. I need to use renderUI for the slider as I want to use the value of the slider (if it already exists) to initialize the slider UI (using the R version of the null coalescing operator). The default value is 1. I've commented out the reactive trigger in this version, which leads to incorrect functionality.

INCORRECT
nopersistence

You can gain persistence of the slider input by uncommenting newChoice() in the modules renderUI, leading to the desired functionality:

CORRECT
persistence

Repeated question:

Why do I need a reactive trigger to make the input slider persistent?

Thanks for your help!

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.