Shiny R observeEvent for selectInput getting triggered at start of Shiny server

Viewed 5592

Below is an example Shiny app:

ui.R:

shinyUI(fluidPage(

  # Application title
  titlePanel("Test select input event"),
  sidebarLayout(
    sidebarPanel(
      selectInput('testSelect', 'Test',choices = c(1,2,3), multiple = FALSE)
    ),
    mainPanel(
    )
  )
))

server.R:

shinyServer(function(input, output) {

  observeEvent(input$testSelect,{ print("I am getting trigerred unnecessarily")})

})

When I start this app the console logs immediately show:

Listening on http://127.0.0.1:5017
[1] "I am getting trigerred unnecessarily"

It seems that observeEvent on a select input is triggered unnecessarily at the start of the app. Can someone please explain this behaviour?

1 Answers

There is an ignoreInit parameter in observeEvent which takes care of such unwanted triggers. The following code will prevent the message from being shown at startup.

library(shiny)

shinyApp(
  selectInput('testSelect', 'Test', choices = c(1, 2, 3)),
  function(input, output, session){
    observeEvent(
      input$testSelect,                                     ## eventExpr
      {print("I am NOT getting trigerred unnecessarily")},  ## handlerExpr
      ignoreInit = TRUE
    )
  }
)

The documentation of the parameter (in ?observeEvent) gives good insights about how observeEvent operates at startup.

ignoreInit

If TRUE, then, when this observeEvent is first created/initialized, ignore the handlerExpr (the second argument), whether it is otherwise supposed to run or not. The default is FALSE. See Details.

The details section clarifies this further.

From Details: By default, observeEvent will run right when it is created (except if, at that moment, eventExpr evaluates to NULL and ignoreNULL is TRUE)

By the time observeEvent is created, input$testSelect will have the value 1 and therefore handlerExpr (i.e. the print command) is triggered unless ignoreInit is set to it's non-default value TRUE.

Related