Haribo
Haribo

Reputation: 2226

Access variable which get update inside the observer event in shiny

I wanted to access a variable which is getting updated/created inside the observeEvent function in shiny app but I can not do it outside of observeEvent function :

## Not working :

library(shiny)

ui <- (fluidPage(
  actionButton("button","Press Me"),
  verbatimTextOutput("data")
))

server <- function (input,output) {
  observeEvent(input$button,{
    x <- 1
  })
output$data <- renderPrint(x)
}
shinyApp (ui=ui,server=server)

## But if I try to access variable inside the observerEvent function it works :

library(shiny)

ui <- (fluidPage(
  actionButton("button","Press Me"),
  verbatimTextOutput("data")
))

server <- function (input,output) {
  observeEvent(input$button,{
    x <- 1
    output$data <- renderPrint(x)
  })

}

shinyApp (ui=ui,server=server)

I also tried to define x=c(), in server side and do the same but no success :

library(shiny)

ui <- (fluidPage(
  actionButton("button","Press Me"),
  verbatimTextOutput("data")
))

server <- function (input,output) {
  x= c()
  observeEvent(input$button,{
    x <- 1
  })

output$data <- renderPrint(x)

}

shinyApp (ui=ui,server=server)

How can I fix the issue ?!

Upvotes: 0

Views: 490

Answers (2)

user12256545
user12256545

Reputation: 3002

Use reactive values :

library(shiny)

ui <- (fluidPage(
  actionButton("button","Press Me"),
  verbatimTextOutput("data")
))

server <- function (input,output) {
  values <- reactiveValues(x=0)
  output$data <- renderPrint({values$x})
  observeEvent(input$button,{
    values$x <- values$x + 1
  })
  
}

shinyApp (ui=ui,server=server)


Upvotes: 0

stefan
stefan

Reputation: 124148

One option to fix that would be to make x a reactiveVal.

library(shiny)

ui <- (fluidPage(
  actionButton("button", "Press Me"),
  verbatimTextOutput("data")
))

server <- function(input, output) {
  x <- reactiveVal()

  observeEvent(input$button, {
   # Assign 1 to the reactive value x
    x(1)
  })
  output$data <- renderPrint(x())
}

shinyApp(ui = ui, server = server)

enter image description here

Upvotes: 1

Related Questions