geotheory
geotheory

Reputation: 23650

R Shiny observeEvent continues to trigger

I'm struggling to get an observeEvent process to run only once after it's triggering event - a button click. This illustrates:

require(shiny)

ui = fluidPage(
  textInput("input_value", '1. input a value. 2. click button. 3. input another value', ''),
  actionButton("execute", 'execute'),
  textOutput('report')
)

server = function(input, output, session) {
  observeEvent(input$execute, {
    output$report = renderText(input$input_value)
  })
}

shinyApp(ui = ui, server = server, options = list(launch.browser = T))

You'll see that after the button has been clicked once, the textOutput becomes responsive to textInput changes rather than button clicks.

I've tried this approach:

server = function(input, output, session) {
  o = observeEvent(input$execute, {
    output$report = renderText(input$input_value)
    o$destroy
  })
}

No effect. I've also tried employing the isolate function with no luck. Grateful for suggestions.

Upvotes: 5

Views: 2369

Answers (2)

Edgar Manukyan
Edgar Manukyan

Reputation: 1301

Alliteratively you can bring the reactive values into an isolated scope of observeEvent() as below:

library(shiny)

ui = fluidPage(
  textInput("input_value", '1. input a value. 2. click button. 3. input another value', ''),
  actionButton("execute", 'execute'),
  textOutput('report')
)

server = function(input, output, session) {
  observeEvent(input$execute, {

    # bringing reactive values into an isolated scope
    inp_val <- input$input_value

    output$report <- renderText(inp_val)
  })
}

shinyApp(ui = ui, server = server, options = list(launch.browser = T))

Upvotes: 0

Chris
Chris

Reputation: 1615

You probably had your isolate() call wrapped around renderText() instead of input$input_value. This should do it for you:

require(shiny)

ui = fluidPage(
  textInput("input_value", '1. input a value. 2. click button. 3. input another value', ''),
  actionButton("execute", 'execute'),
  textOutput('report')
)

server = function(input, output, session) {
  observeEvent(input$execute, {
    output$report = renderText(isolate(input$input_value))
  })
}

shinyApp(ui = ui, server = server, options = list(launch.browser = T))

Upvotes: 4

Related Questions