I would like to use a reactive value to load control a selectizeInput widget. I can do this with a simple shiny app, but I can't seem to be able to replicate it when I try to reorganize it in a module.
In the following code I have a simple app with an input widget and a button. After pressing the button, I want the selectizeInput()
widget to be updated with the values stored in the reactive variable.
library(shiny)
# GLOBAL VAR TO BE LOADED after pressing the button
# -------------
STORED <- reactiveValues(choices = c("a", "b", "c")
, selected = c("c"))
# UI
# -------------
ui <- fixedPage(
wellPanel(
# input widget
selectInput("widget1"
, "label"
,choices = c("WRONG A","WRONG B","WRONG C")
,selected="WRONG A"
)
# update button
, actionButton("plotBtn"
, "update"
, class = "btn-primary")
)
)
# SERVER
# -------------
server <- function(input, output, session) {
observeEvent(input$plotBtn,{
message("update button was pressed")
updateSelectInput(session
,"widget1"
,choices = STORED$choices
, selected = STORED$selected
)
})
}
# APP
shinyApp(ui, server)
after pressing the button, the widget is correctly updated with "c" selected, and the choices are correctly imported. However, when I try to write it as a shiny module, the button doesn't work.
library(shiny)
# INIT VARS TO BE LOADED AFTER PRESSING THE BUTTON
# ------------------------------------------------------------------------------
STORED <- reactiveValues(choices = c("a", "b", "c")
, selected = c("c"))
# MODULE SELECTIZEINPUT
# ------------------------------------------------------------------------------
input_widgetUI <- function(id) {
ns <- NS(id)
selectizeInput(ns("input_widget")
, label = "label"
, choices = c("WRONG A","WRONG B","WRONG C")
, selected = "WRONG A"
)
}
# MODULE BUTTON
# ------------------------------------------------------------------------------
plotBtnUI <- function(id){
ns <- NS(id)
fluidPage(actionButton(ns("plotBtn"), "update", class = "btn-primary"))
}
plotBtn <- function(input, output, session) {
ns <- session$ns
print("Loading plotBtn()")
observeEvent(input$plotBtn, {
message("update button was pressed")
updateSelectizeInput(session
, ns("widget1")
, choices = STORED$choices
, selected= STORED$selected
)
})
}
# #############################################################################
# SHINY APP
# #############################################################################
ui <- fixedPage(
wellPanel(
input_widgetUI("widget1")
, plotBtnUI("button")
)
)
server <- function(input, output, session) {
callModule(plotBtn, "button")
}
shinyApp(ui, server)
I belive I might be using the wrong ID. Any suggestion is very welcome! Thanks