Home > Software design >  Access variable which get update inside the observer event in shiny
Access variable which get update inside the observer event in shiny

Time:12-22

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 ?!

CodePudding user response:

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

CodePudding user response:

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)


  • Related