0

I have a shiny app, each module is it's own file. Each module get's an ns <- NS(id). When I adress an Element, say a button from one of those modules with observeEvent it works if I just hardcode an ID in the module, but not if I use ns(). What am I doing wrong?

Module:

mod_add_element_ui <- function(id){
  ns <- NS(id)
  tagList(
    shiny::actionButton(ns("add_element"), "add new element", icon = icon("plus-square"))
  )
}
    
mod_add_element_server <- function(id){
  moduleServer( id, function(input, output, session){
    ns <- session$ns     
  })
}

app_ui:

app_ui <- function(request) {
  tagList(
    fluidPage(
      mod_add_element_ui("add_element_ui_1"),
      div(id="add_here")
    )
  )
}

app_server:

app_server <- function( input, output, session ) {
  mod_add_element_server("add_element_ui_1")
  observeEvent(input$add_element,
               {
                 mod_add_element_server(id="mod")
                 insertUI(selector = "#add_here", ui = mod_add_element_ui("mod"))
               }
  )  
}
PanikLIji
  • 31
  • 4
  • 1
    where is `mod_add_cost_element_server(...)` defined? – YBS Jul 12 '22 at 14:45
  • That was just a copying mistake, I changed the names for this question to make it all a bit shorter, it's supposed to just be mod_add_element_server. I corrected it. – PanikLIji Jul 12 '22 at 14:53

1 Answers1

0

Try this

mod_add_element_ui <- function(id){
  ns <- NS(id)
  tagList(
    shiny::actionButton(ns("add_element"), "add new element", icon = icon("plus-square"))
  )
}

mod_add_element_server <- function(id){
  moduleServer( id, function(input, output, session){
    ns <- session$ns     
    return(reactive(input$add_element))
  })
}

app_ui <- function(request) {
  tagList(
    fluidPage(
      mod_add_element_ui("add_element_ui_1"),
      div(id="add_here")
    )
  )
}

app_server <- function( input, output, session ) {
  added_element <- mod_add_element_server("add_element_ui_1")
  observeEvent(added_element(),
               {
                 mod_add_element_server(id="mod")
                 insertUI(selector = "#add_here", ui = mod_add_element_ui("mod"))
               }
  )  
}

shinyApp(app_ui, app_server)
YBS
  • 19,324
  • 2
  • 9
  • 27
  • No sorry, that solution doesn't work, it just adds the module from the start and does nothing when the button is clicked. Everything works if I just remove the NS() and give the button the id=add_element instead of ns(add_element), debugging a bit shows me that observeElement just isn't called when the id is ns(add_element), can anyone tell me what's happening here? – PanikLIji Jul 18 '22 at 13:03