Search code examples
rshinyshiny-reactivity

How to use a reactive expression in updateSelectInput?


I know that reaction expressions must be used in reactive contexts and updateSelectInput is not a reactive context. I have used a reprex below but in my real application i get some data processed in a reactive() way. I want to use the first column of that data to be used in my select input and i cannot figure out how to do that:

ui = fluidPage(
  selectInput("state", "Choose a state:",choices = NULL
              
  ),
  textOutput("result")
)

server <- function(input, output, session) {
  
    
    updateSelectInput(session, "state",
                      choices = hello())
    hello<-reactive({mtcars[1]})
    
}

Solution

  • Just wrap updateSelectInput in an observer:

    library(shiny)
    
    ui = fluidPage(
      selectInput("state", "Choose a state:", choices = NULL),
      textOutput("result")
    )
    
    server <- function(input, output, session) {
      hello <- reactive({mtcars[1]})
      observe({
        freezeReactiveValue(input, "state")
        updateSelectInput(session, "state", choices = hello())
        })
    }
    
    shinyApp(ui, server)