Search code examples
rshinyshinydashboardshinyappsselectinput

updateSelectInput is overwritten by a selectInput in a shiny app


In the example below the action button would update the select input values. However, the second selection input is dependent on the first one and when the action button is selected the update to "virginica" does not occur.

ui <- fluidPage(

        actionButton(inputId = "action", label = "click"),
        uiOutput("select_col"),
        uiOutput("select_species")
    
    )
    
    #
    server <- function(input, output) {
    
    output$select_col <- renderUI({
        selectInput(inputId = "select_col", 
                label = "select_col", 
                choices = colnames(iris))
    })
    
    output$select_species <- renderUI({
        selectInput(inputId = "select_species",
                label = "Species",
                choices = unique(iris[ ,input$select_col]))
    })
    
    observeEvent(input$action, {
        updateSelectInput(inputId = "select_col", selected = "Species")
        updateSelectInput(inputId = "select_species", selected = "virginica")
    })
    
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server)

I expect the following result: 'Species'in selectinput 'select_col' and setosa in selectinput 'Species'


Solution

  • That should work:

      xxx <- reactiveVal(NULL)
      
      observeEvent(input$action, {
        updateSelectInput(inputId = "select_col", selected = "Species")
        xxx(TRUE)
      })
      
      observeEvent(xxx(), {
        updateSelectInput(inputId = "select_species", selected = "virginica")
        xxx(NULL)
      })
    

    EDIT

    No that doesn't work. Here is a solution using the delay function of the shinyjs package:

      observeEvent(input$action, {
        updateSelectInput(inputId = "select_col", selected = "Species")
        delay(0, updateSelectInput(inputId = "select_species", selected = "virginica"))
      })
    

    Don't forget:

    library(shiny)
    library(shinyjs)
    
    ui <- fluidPage(
      useShinyjs(), # <- don't forget that
      actionButton(inputId = "action", label = "click"),
      ......