I’m wrestling with the best template to use going forward for my namespace modules in R Shiny. I show two sets of code below that do the exact same thing using namespace modules, Example 1 and Example 2. They use different structures. They both simply add a value of 10 to the slider input values for the sake of easy example. Example 1 is one alternative that someone pointed me to. Example 2 is the method that I’ve been using, and I find it easier to visualize than Example 1, but I was told it is an outdated form of module.
Is Example 2 an outdated method? If true, why would Example 1 be a better method? Is there an optimal method these days?
Example 1:
library(shiny)
mod1_ui <- function(id) {
ns <- NS(id)
tagList(textOutput(ns("result_x")))
}
mod1_server <- function(id) {
moduleServer(id, function(input, output, session) {
observe({
session$userData$result_x(session$userData$x_value() + 10)
})
output$result_x <- renderText({
paste("Mod 1 Result for X = X + 10:", session$userData$result_x())
})
})
}
# Main App:
ui <- fluidPage(
mainPanel(
sliderInput("x_value", "X Value:", min = 0, max = 10, value = 0),
mod1_ui("mod1")
)
)
server <- function(input, output, session) {
session$userData$x_value <- reactiveVal(0)
session$userData$result_x <- reactiveVal(0)
observeEvent(input$x_value, {session$userData$x_value(input$x_value)})
mod1_server("mod1")
}
shinyApp(ui, server)
Example 2:
library(shiny)
mod1_ui <- function(id) {
ns <- NS(id)
tagList(textOutput(ns("result_x")))
}
mod1_server <- function(id, common, input) {
moduleServer(id, function(input, output, session) {
output$result_x <- renderText({
paste("Mod 1 Result for X = X + 10:", common$x_value() + 10)
})
})
}
# Main App:
ui <- fluidPage(
mainPanel(
sliderInput("x_value", "X Value:", min = 0, max = 10, value = 0),
mod1_ui("mod1")
)
)
server <- function(input, output, session) {
common <- reactiveValues(
x_value = reactive(input$x_value)
)
mod1_data <- mod1_server("mod1", common, input)
}
shinyApp(ui, server)