Debian Codegraph @

man/moduleServer.Rd

raw
1 % Generated by roxygen2: do not edit by hand
2 % Please edit documentation in R/modules.R
3 \name{moduleServer}
4 \alias{moduleServer}
5 \title{Shiny modules}
6 \usage{
7 moduleServer(id, module, session = getDefaultReactiveDomain())
8 }
9 \arguments{
10 \item{id}{An ID string that corresponds with the ID used to call the module's
11 UI function.}
12
13 \item{module}{A Shiny module server function.}
14
15 \item{session}{Session from which to make a child scope (the default should
16 almost always be used).}
17 }
18 \value{
19 The return value, if any, from executing the module server function
20 }
21 \description{
22 Shiny's module feature lets you break complicated UI and server logic into
23 smaller, self-contained pieces. Compared to large monolithic Shiny apps,
24 modules are easier to reuse and easier to reason about. See the article at
25 \url{https://shiny.rstudio.com/articles/modules.html} to learn more.
26 }
27 \details{
28 Starting in Shiny 1.5.0, we recommend using \code{moduleServer} instead of
29 \code{\link[=callModule]{callModule()}}, because the syntax is a little easier
30 to understand, and modules created with \code{moduleServer} can be tested with
31 \code{\link[=testServer]{testServer()}}.
32 }
33 \examples{
34 # Define the UI for a module
35 counterUI <- function(id, label = "Counter") {
36 ns <- NS(id)
37 tagList(
38 actionButton(ns("button"), label = label),
39 verbatimTextOutput(ns("out"))
40 )
41 }
42
43 # Define the server logic for a module
44 counterServer <- function(id) {
45 moduleServer(
46 id,
47 function(input, output, session) {
48 count <- reactiveVal(0)
49 observeEvent(input$button, {
50 count(count() + 1)
51 })
52 output$out <- renderText({
53 count()
54 })
55 count
56 }
57 )
58 }
59
60 # Use the module in an app
61 ui <- fluidPage(
62 counterUI("counter1", "Counter #1"),
63 counterUI("counter2", "Counter #2")
64 )
65 server <- function(input, output, session) {
66 counterServer("counter1")
67 counterServer("counter2")
68 }
69 if (interactive()) {
70 shinyApp(ui, server)
71 }
72
73
74
75 # If you want to pass extra parameters to the module's server logic, you can
76 # add them to your function. In this case `prefix` is text that will be
77 # printed before the count.
78 counterServer2 <- function(id, prefix = NULL) {
79 moduleServer(
80 id,
81 function(input, output, session) {
82 count <- reactiveVal(0)
83 observeEvent(input$button, {
84 count(count() + 1)
85 })
86 output$out <- renderText({
87 paste0(prefix, count())
88 })
89 count
90 }
91 )
92 }
93
94 ui <- fluidPage(
95 counterUI("counter", "Counter"),
96 )
97 server <- function(input, output, session) {
98 counterServer2("counter", "The current count is: ")
99 }
100 if (interactive()) {
101 shinyApp(ui, server)
102 }
103
104 }
105 \seealso{
106 \url{https://shiny.rstudio.com/articles/modules.html}
107 }