简体   繁体   中英

R shiny: different behaviours of observeEvent and eventReactive

The shiny app below displays an editable table built with rhandsontable() .

Question : Can you explain me why "ping" is printed to the console whenever an edit is made to the data table while "pong" is never printed.

library(shiny)

ui <- fluidPage(
  rhandsontable::rHandsontableOutput(
    outputId = "data")
)

server <- function(input, output, session) {
  
  data <- data.frame(a = 1, b = 2, c = 3)
  
  output$data <- rhandsontable::renderRHandsontable({
    rhandsontable::rhandsontable(
      selectCallback = TRUE,
      data = data)
  })
  
  observeEvent(input$data$changes$changes, {
    print("ping")
  })
  
  edits <- eventReactive(input$data$changes$changes, {
    print("pong")
  })
  
}

shinyApp(ui = ui, server = server)

It's because edits() isn't called thereafter, so shiny thinks you don't need it, hence no reason to do any work on it, you need to add where it should go or what you want to do with it:

library(shiny)

ui <- fluidPage(
    rhandsontable::rHandsontableOutput(
        outputId = "data")
)

server <- function(input, output, session) {
    
    data <- data.frame(a = 1, b = 2, c = 3)
    
    output$data <- rhandsontable::renderRHandsontable({
        rhandsontable::rhandsontable(
            selectCallback = TRUE,
            data = data)
    })
    
    observeEvent(input$data$changes$changes, {
        print("ping")
    })
    
    edits <- eventReactive(input$data$changes$changes, {
        print("pong")
    })
    
    observe({
        edits()
    })
    
}

shinyApp(ui = ui, server = server)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM