Skip to content

Instantly share code, notes, and snippets.

@strboul
Created January 2, 2019 20:06
Show Gist options
  • Save strboul/01c942c77a9b57411f200ea8729fac16 to your computer and use it in GitHub Desktop.
Save strboul/01c942c77a9b57411f200ea8729fac16 to your computer and use it in GitHub Desktop.
Shiny updateTextInput between modules by passing the session object in between
library(shiny)
# MODULES ----------------------------------------------------------------------
text_ui <- function(id) {
ns <- shiny::NS(id)
shiny::tagList(
textInput(ns("text"), "Write here"),
verbatimTextOutput(ns("display"))
)
}
text_server <- function(input, output, session) {
rv.text <- reactiveValues(val = FALSE)
observeEvent(input$text, {
rv.text$val <- input$text
})
output$display <- renderText({
rv.text$val
})
return({ session })
}
reset_btn_ui <- function(id) {
ns <- shiny::NS(id)
shiny::tagList(
actionButton(ns("reset"), "Reset")
)
}
reset_btn_server <- function(input, output, session, TextModuleSession) {
observeEvent(input$reset, {
updateTextInput(session = TextModuleSession, "text", value = "")
})
}
# MAIN -------------------------------------------------------------------------
ui <- fluidPage(
fluidRow(
column(6,
text_ui("text"),
reset_btn_ui("btn")
)
)
)
server <- function(input, output, session) {
TextModuleSession <- callModule(module = text_server,
id = "text")
callModule(module = reset_btn_server,
id = "btn",
TextModuleSession)
}
# Shiny update and reset input with Shiny modules
# Related source: https://stackoverflow.com/a/51757792/
shinyApp(ui, server)
@rhetor
Copy link

rhetor commented Jul 16, 2021

thanks for this example, passing 'TextModuleSession' is very useful !

@lhabegger
Copy link

lhabegger commented Nov 3, 2022

Nice! Helped me solving a tidy bit different example, where an actionButton inside a module should trigger an action outside of the module. Passing the mainSession object inside the module worked:

mod_module1_server("module1_1", mainSession = session)

and then in the module e.g. updating the currently selected tab of a tabsetPanel by using an actionButton within the module UI worked like this:

observeEvent(input$actionButton1, { updateTabItems(session = mainSession, inputId = "sidebarMenu", selected = "tab1") })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment