Hi,
I have made a reproducible example below to show my problem.
I am using mpg dataset which contains some fuel economy data by car manufacturers and models.
I have two selectInput's each for manufacturer and model selection. I have defined the choices argument for manufacturer input in ui and I expect the list of model input could be updated depending on the value of manufacturer. And a subset of mpg table by selected manufacturer/model is shown as an output.
I have realised my app runs twice when I initialise the app or when I select a different value in manufacturer input. I insert str(input$model) before generating the underlying table to capture this phenomenon. When I initialise the app, input$model value is "" the first time and gives a blank table and only then server runs again and input$model value is updated to give a table. And if you exam the input$model value in observeEvent(filtered_models(), { before and after updateSelectizeInput, you will see input$model value stays the same and this confuses me.
The double-run is not ideal especially if some big tables with intensive calculation are needed. Will be appreciated if someone could help me with this issue.
library(shiny)
library(ggplot2) # use mpg dataset in ggplot2
library(data.table)
dt <- as.data.table(mpg)
manufacturer_list <- dt[, unique(manufacturer)]
ui <- fluidPage(
selectInput(inputId = "manufacturer",
label = "Manufacturer",
choices = manufacturer_list,
selected = manufacturer_list[1]
),
selectInput(inputId = "model",
label = "Model",
choices = NULL
),
tableOutput("table")
)
server <- function(input, output, session) {
filtered_models <- reactive({dt[manufacturer == input$manufacturer, unique(model)]})
observeEvent(filtered_models(), {
updateSelectizeInput(session, 'model', choices = c(filtered_models()), selected = filtered_models()[1])
})
filtered_mpg <- reactive({
# str(input$model)
dt[manufacturer == input$manufacturer & model == input$model]
})
output$table <- renderTable(filtered_mpg())
}
shinyApp(ui, server)