Tim Hargreaves
Tim Hargreaves

Reputation: 332

How to run code before switching to new tab in R Shiny?

Here is a minimal reproducible example of my problem:

library(shiny)

ui <- fluidPage(
  tabsetPanel(
    tabPanel(
      "Tab1",
      actionButton("button", "Click me")
    ),
    tabPanel(
      "Tab2",
      plotOutput("plot")
    )
  )
)

server <- function(input, output) {
  myPlot <- eventReactive(input$button, {
    Sys.sleep(5)
    hist(rnorm(100))
  })

  output$plot <- renderPlot({
    myPlot()
  })
}

shinyApp(ui = ui, server = server)

In its current state, I have two tabs - one with a button and one that contains a plot output. I would like the app to behave in such a way that if I am in tab 1 and press the action button, and wait 5 seconds, I can then go to tab 2 and should see the plot output immediately. At the moment, however, when I go to tab 2, the 5-second wait begins from then. How could I change my code so that it behaves as I intended?

Upvotes: 1

Views: 743

Answers (1)

A. Suliman
A. Suliman

Reputation: 13125

We can use observeEvent instead of eventReactive

server <- function(input, output) {
    data<-reactiveValues(myPlot=NULL)
    observeEvent(input$button, {
      Sys.sleep(5)
      data$myPlot <- ggplot(mtcars)+geom_abline() #
    })
    output$plot <- renderPlot({
      data$myPlot
    })
  }

Upvotes: 3

Related Questions