Search code examples
rshinyreactivehandsontablerhandsontable

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)

Solution

  • 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)