rshinyshinymodules

How to return a selected input from a module in a shiny app?


Objective

I have a module in a shiny app in R where I want to render a selected input based on the choices that come from a database. I want to return the selected choice as a reactive from this module.

Reproducible Example:

Why is the selected_choice always NULL when I run the app?

selector_input_ui <- function(id) {
  ns <- NS(id)
  tagList(
    uiOutput(ns("selectoor"))
  )
  
}

selector_input_server <- function(id) {
  
  moduleServer(
    id,
    function(input, output, session) {
      
      res_list <- reactive({
        # code for creating a list from data in a database
        ## mock-up list:
        list("choice1", "choice2", "choice3")
      })
      
      output$selectoor <- renderUI({
        selectInput(inputId = "selected",
                    label = "Select",
                    choices = res_list())
      })
      
      return(
        reactive({
          input$selected
        })
      )
    }
  )
}



library(shiny)

ui <- fluidPage(
  selector_input_ui("menu"),
  verbatimTextOutput("printt")
)

server <- function(input, output, session) {
  selected_choice <- selector_input_server("menu")
  
  output$printt <- renderPrint({
    
    selected_choice()
  })
}

shinyApp(ui, server)

Solution

  • You are missing a ns in the selectInput

    selector_input_ui <- function(id) {
      ns <- NS(id)
      tagList(
        uiOutput(ns("selectoor"))
      )
      
    }
    
    selector_input_server <- function(id) {
      
      moduleServer(
        id,
        function(input, output, session) {
          ns <- session$ns
          res_list <- reactive({
            # code for creating a list from data in a database
            ## mock-up list:
            list("choice1", "choice2", "choice3")
          })
          
          output$selectoor <- renderUI({
            selectInput(inputId = ns("selected"),
                        label = "Select",
                        choices = res_list() #,
                        # selected = res_list()[[1]]
                        )
          })
          
          return(
            reactive({
              input$selected
            })
          )
        }
      )
    }
    
    
    
    library(shiny)
    
    ui <- fluidPage(
      selector_input_ui("menu"),
      verbatimTextOutput("printt")
    )
    
    server <- function(input, output, session) {
      selected_choice <- selector_input_server("menu")
      
      output$printt <- renderPrint({
        
        selected_choice()
      })
    }
    
    shinyApp(ui, server)