Home > Enterprise >  change dataset with dropdown
change dataset with dropdown

Time:07-01

I am developing a Shiny app in golem that displays data in a DT. I want the user to be able to select a dataset. This is the first time I am trying to pass reactive values from a Shiny module, and for some reason the DT is not updating when another dataset is selected. Reprex below, thanks for your help!

reprex::reprex({
  
  library(tidyverse)
  library(shiny)
  

# modules -----------------------------------------------------------------
## filter_source----------------------------------------------------------
  mod_filter_source_ui <- function(id) {
    ns <- NS(id)
    tagList(
      shiny::selectInput(
        ns("dataset"),
        label = "select dataset",
        choices = c("cars", "pressure", "diamonds"),
        selectize = TRUE
      ))
  }
  
  mod_filter_source_server <- function(id) {
    moduleServer(id, function(input, output, session) {
      ns <- session$ns
      df_dataset <- shiny::reactive({
        switch(input$dataset,
               "cars"= cars,
               "pressure" = pressure,
               "diamonds" = diamonds)
      })
      return(df_dataset)
    })
  }
  

## render_table ------------------------------------------------------------
  mod_table_ui <- function(id){
    ns <- NS(id)
    tagList(
      DT::dataTableOutput(ns("table_out"))
    )
  }

  mod_table_server <- function(id, df){
    moduleServer( id, function(input, output, session){
      ns <- session$ns
      output$table_out <- DT::renderDataTable(df)
      
    })
  }


# ui ----------------------------------------------------------------------

  app_ui <- function(request) {
    tagList(
      fluidPage(
        mod_filter_source_ui("selected_dataset"),
        mod_table_ui("main_table")
      )
    )
  }
  
# server ------------------------------------------------------------------
  app_server <- function(input, output, session) {
    df_dataset_val <- mod_filter_source_server("selected_dataset")
    mod_table_server("main_table", df = df_dataset_val())
  }
  

# run ---------------------------------------------------------------------

shinyApp(app_ui, app_server)  
  
})

CodePudding user response:

There is a subtle difference between a reactive (df_dataset_val) and the value of a reactive (df_dataset_val()). You got it right in the definition of your filter module server and returned the reactive rather than its value. But you got it wrong in your call to your table module server and passed the current value of the reactive, rather than the reactive itself.

Replace mod_table_server("main_table", df = df_dataset_val()) with mod_table_server("main_table", df = df_dataset_val) and you should be good to go.

See the highlighted text at the end of the "Writing server functions" section of this RStudio article.

  • Related