luismf
luismf

Reputation: 371

Updating non-reactive values in R Shiny

I have the following example:

library(shiny)

ui <- fluidPage(
  textOutput("out"),
  actionButton("plusX", "Increase X"),
  actionButton("redraw", "redraw")
)

server <- function(input, output, session) {
  x <- 0
  observeEvent(input$plusX, {x <<- x+1})
  output$out <- renderText({
    input$redraw
    x
  })
}

shinyApp(ui, server)

Is this considered an anti-pattern in Shiny to modify a non-reactive variable in this way? Obviating the super assignment which can be problematic by itself.

I know this could be done, for example with a reactiveVal to store X, and isolate to obtain a similar result. This second way seems clearer and that would be my usual choice, but I was wondering if there any caveats in the first one, or it is possible way of doing that.

library(shiny)

ui <- fluidPage(
  textOutput("out"),
  actionButton("plusX", "Increase X"),
  actionButton("redraw", "redraw")
)

server <- function(input, output, session) {
  x <- reactiveVal(0)
  observeEvent(input$plusX, {x(x()+1)})
  output$out <- renderText({
    input$redraw
    isolate(x())
  })
}

shinyApp(ui, server)

Upvotes: 1

Views: 653

Answers (1)

koolmees
koolmees

Reputation: 2783

In this example there is no important difference between both codes as you are not using the benefit of ReactiveVal.

The benefit of ReactiveVal is that it has a reactive nature and thus can interact with other reactive elements.

Try for example to add a table to your code that depends on x:

output$tab <- renderTable({data.frame(y = x)})

(x() in the case of ReactiveVal)

The difference you will see that in the case of ReactiveVal the table automatically updates with plusX whereas in the case of the regular variable it does not update.

Upvotes: 1

Related Questions