Golem: Código no server funciona, mas o módulo não

Bom dia, pessoal! Tudo bem?

Criei um app via Shiny, mas ele ficou grande e então decidi passar para o Golem.

Acontece que estou tendo um problema, o módulo do server não funciona.

Meu app_ui.R:

#' The application User-Interface
#'
#' @param request Internal parameter for `{shiny}`.
#'     DO NOT REMOVE.
#' @import shiny
#' @noRd
app_ui <- function(request) {
   tagList(# Leave this function for adding external resources
      golem_add_external_resources(),
      # Your application UI logic
      fluidPage(
         theme = shinythemes::shinytheme("united"),
         navbarPage(
            # theme = "cerulean",  # <--- To use a theme, uncomment this
            "App Cool Name",
            tabPanel(
               "Inicial",
               h5("Dados Gerais"),
               fluidRow(
                  shinydashboard::valueBoxOutput(outputId = "data_msg",
                                                 width = "3"),
                  shinydashboard::valueBoxOutput(outputId = "data_groups",
                                                 width = "3")
                  
               ))))
)
}

#' Add external Resources to the Application
#'
#' This function is internally used to add external
#' resources inside the Shiny application.
#'
#' @import shiny
#' @importFrom golem add_resource_path activate_js favicon bundle_resources
#' @noRd
golem_add_external_resources <- function() {
  add_resource_path(
    "www",
    app_sys("app/www")
  )

  tags$head(
    favicon(),
    bundle_resources(
      path = app_sys("app/www"),
      app_title = "reprex"
    )
    # Add here other external resources
    # for example, you can add shinyalert::useShinyalert()
  )
}

Meu app_server.R:

#' The application server-side
#'
#' @param input,output,session Internal parameters for {shiny}.
#'     DO NOT REMOVE.
#' @import shiny
#' @noRd
app_server <- function(input, output, session) {
  # Your application server logic
   con <- DBI::dbConnect(drv = RSQLite::SQLite(),
                         dbname = "data-raw/data_base.db")

   output$data_msg <- shinydashboard::renderValueBox({
      data_msg <-
         as.character(
            DBI::dbGetQuery(
               con,
               "select count(*) as msg
                                                from cool_name
                                              where network IN ('data')"
            )
         )
      shinydashboard::valueBox(
         value = data_msg,
         subtitle = "Nº Mensagens",
         color = "yellow",
         width = "3 col-lg-2"
      )
   })

  

   output$data_group <- shinydashboard::renderValueBox({
      data_group <-
         as.character(
            DBI::dbGetQuery(
               con,
               "select sum(a.cnt)
                                      from (
                                              select count(distinct(group_id)) as cnt
                                              from cool_name
                             where network IN ('groups')
                                              group by group_id
                                           ) as a"
            )
         )

      shinydashboard::valueBox(
         value = data_group,
         subtitle = "Nº de Grupos",
         color = "yellow",
         width = "3"
      )
   })

}

Até aqui, tudo bem. Dessa forma funciona normal.

Aí eu usei o golem::add_modules("test").

Meu mod_test.R:

#' test UI Function
#'
#' @description A shiny Module.
#'
#' @param id,input,output,session Internal parameters for {shiny}.
#'
#' @noRd
#'
#' @importFrom shiny NS tagList
mod_test_ui <- function(id){
  ns <- NS(id)
  tagList(
     # Frontpage - boxes - start -----------------------------------------------
     shinydashboard::valueBoxOutput(outputId = "data_msg",
                                    width = "3"),
     shinydashboard::valueBoxOutput(outputId = "data_groups",
                                    width = "3")
     
  )
}

#' test Server Functions
#'
#' @noRd
mod_test_server <- function(id){
  moduleServer( id, function(input, output, session){
    ns <- session$ns

    con <- DBI::dbConnect(drv = RSQLite::SQLite(),
                          dbname = "data-raw/data_base.db")
    
    output$data_msg <- shinydashboard::renderValueBox({
       data_msg <-
          as.character(
             DBI::dbGetQuery(
                con,
                "select count(*) as msg
                                                from cool_name
                                              where network IN ('data')"
             )
          )
       shinydashboard::valueBox(
          value = data_msg,
          subtitle = "Nº Mensagens",
          color = "yellow",
          width = "3 col-lg-2"
       )
    })
    
    
    
    output$data_group <- shinydashboard::renderValueBox({
       data_group <-
          as.character(
             DBI::dbGetQuery(
                con,
                "select sum(a.cnt)
                                      from (
                                              select count(distinct(group_id)) as cnt
                                              from cool_name
                             where network IN ('groups')
                                              group by group_id
                                           ) as a"
             )
          )
       
       shinydashboard::valueBox(
          value = data_group,
          subtitle = "Nº de Grupos",
          color = "yellow",
          width = "3"
       )
    })
    
  })
}

## To be copied in the UI
# mod_test_ui("test_1")

## To be copied in the server
# mod_test_server("test_1")

Mas quando eu substituo os códigos na UI e no Server por mod_test_ui("test_1") e mod_test_server("test_1"), ele para de funcionar.

Percebi que se eu adicionar o mod_test_ui("test_1") e deixar o código original no Server, ele funciona!

Vocês tem alguma ideia do que eu possa estar me esquecendo aqui??

1 curtida

Theodoro, módulos não são uma funcionalidade do Golem, mas sim do Shiny. Você pode dar uma olhada na documentação completa aqui: Shiny - Modularizing Shiny app code.

Se eu entendi direito, você não está usando o namespace corretamente. Acho que você precisaria usar a função ns() em volta dos IDs da sua UI (ou seja, ns("data_msg") e ns("data_groups")).

3 curtidas

AAAA não acredito que não reparei nisso haha

Muuuito obrigado !

Vou ler essa documentação! Valeu!

1 curtida

isso acontece comigo com certa frequência auhaiuhaiuhauiahuiah
esquecer do ns() e ficar um tempo tentando entender pq o app não funciona como deveria

1 curtida

nossa, fiquei um tempão tentando entender hahaha

2 curtidas