Declaring uiOutput widgets on unopened tabs

Viewed 49

I'm creating an R Shiny app that runs a function based off of many reactive widgets on multiple tabs. A problem I'm running into is that when the app is initially launched, I need to select the tabs that contain the respective reactive widgets before the widget's id is recognized in the "input". Is there a way to either 1.) have the app recognize all the reactive widgets when the app is deployed or 2.) alter the "input" initially to contain initial values for the reactive widget ids. Here is a simple example of the problem:

ui <- shinyUI(fluidPage(
  sidebarLayout(
    sidebarPanel(
      tabsetPanel(
        tabPanel("tab 1", numericInput("a", "A", 2)),
        tabPanel("tab 2", uiOutput("bUI"))
      )
    ),
    mainPanel(
      verbatimTextOutput("a_b")
    )
  )
))


server <- function(input, output, session){
  output$bUI <- renderUI({
    numericInput("b", "B", 3)
  })
  
  output$a_b <- renderPrint(input$a * input$b)
}

shinyApp(ui = ui, server = server)

I initially get an output of interger(0) instead of the desired 6.

Note, I do not want to require the user to have to select all the tabs. i.e. I don't want to use req or validate to push the user to click through the tabs.

1 Answers

I added an intermediate check if input$b is truthy. If not, a default 3 is used:

library('shiny')
ui <- shinyUI(fluidPage(
  sidebarLayout(
    sidebarPanel(
      tabsetPanel(
        tabPanel("tab 1", numericInput("a", "A", 2)),
        tabPanel("tab 2", uiOutput("bUI"))
      )
    ),
    mainPanel(
      verbatimTextOutput("a_b")
    )
  )
))


server <- function(input, output, session){
  output$bUI <- renderUI({
    numericInput("b", "B", 3)
  })
  
  safe_b <- eventReactive(input$b, if(isTruthy(input$b)) input$b else 3, ignoreNULL = F)
  
  output$a_b <- renderPrint(input$a * safe_b())
}

shinyApp(ui = ui, server = server)
Related