I have a simple shiny mechanism question and I am not understanding why and how I could answer it.
I have an app where an observeEvent action is inside a module server. This server is associated to a tabPanel.
My problem is : if I click on the button, close the modal, change panel and then go back to Home one, the modal shows again. How to prevent this behavior ? Should I “reset” the actionButton value or is it a reactivity mistake ?
library(shiny)
mod_test_ui <- function(id){
ns <- NS(id)
tagList(
actionButton(ns("click_me"), "Click")
)
}
mod_results_server <- function(id){
moduleServer(id, function(input, output, session){
ns <- session$ns
observeEvent(input$click_me, {
showModal(modalDialog(id = "mymodalstudy", "Here is a modal"))
})
})
}
ui <- bootstrapPage(
tabsetPanel(id = "mytab",
tabPanel("Home", mod_test_ui("Test")),
tabPanel("Other", p("Other content"))))
server <- function(input, output) {
observeEvent(input$mytab,{
if(input$mytab == "Home") {
mod_results_server("Test")
}
})
}
# Return a Shiny app object
shinyApp(ui = ui, server = server)
The moduleServer()
has to be created once.
I fill its name in react$loaded_modules
to verify if it exists.
You can see that:
- the timestamp stays identical at its creation time if you comme back to a modal yet created.
- but if you change the text input, it’s changed but the timestamp remains the old one
library(shiny)
mod_test_ui <- function(id){
ns <- NS(id)
tagList(
actionButton(ns("click_me"), "Click")
)
}
mod_results_server <- function(id, blatime,input_bla_react){
moduleServer(id, function(input, output, session){
ns <- session$ns
observeEvent(c(input$click_me,input_bla_react), {
if (!(is.null(input$click_me)) && input$click_me >0 ) {
showModal(modalDialog(id = "mymodalstudy",
paste("Here is a modal ",id, blatime, input_bla_react(), sep =" " )
))
}
})
})
}
ui <- bootstrapPage(
textInput("mytext", label='Text Input', value='nothing'),
p('Loaded modules'),
verbatimTextOutput('modules'),
tabsetPanel(id = "mytab",
tabPanel("Home", mod_test_ui("Home")),
tabPanel("OtherA", p("Other content"),mod_test_ui("OtherA")),
tabPanel("OtherB", p("Other content"),mod_test_ui("OtherB")),
tabPanel("OtherC", p("Other content"),mod_test_ui("OtherC")),
selected ="Home"
)
)
server <- function(input, output) {
react <- reactiveValues(
loaded_modules=c()
)
output$modules <- renderPrint({react$loaded_modules })
observeEvent(input$mytab,{
selected_tab=ifelse (is.null(input$mytab),"Home",input$mytab)
if (length(intersect(react$loaded_modules,selected_tab)) ==0 ) {
react$loaded_modules<- unique(c(react$loaded_modules,selected_tab))
mod_results_server(selected_tab,Sys.time(),reactive(input$mytext))
}
},
ignoreNULL = FALSE)
}
# Return a Shiny app object
shinyApp(ui = ui, server = server)
3