How to make sure a button is pressed the first time a shiny app gets run?

So I have a set of computations that is generated when a button is pressed. But I want the computation to be generated when the app is launched initially. Which basically translates to having that button automatically pressed upon launch of the app.

How can that be done in R Shiny app?

Upvotes: 2

Views: 803

Answers (1)

Shree
Shree

Reputation: 11150

Here's one way using shinyjs::click() function using which you can simulate a button click when app is initialized. Run the app with and without the observe to see the difference. -

library(shiny)
library(shinyjs)

init <- 5
shinyApp(
  ui = fluidPage(
    useShinyjs(),
    br(),
    actionButton("add", "Add"),
    verbatimTextOutput("test")
  ),
  server = function(input, output, session) {
    
    o <- observe({
      shinyjs::click("add")
      o$destroy() # destroy observer as it has no use after initial button click
    })
    
    val <- eventReactive(input$add, {
      init + 1
    })
    
    output$test <- renderPrint(val())
  }
)

Upvotes: 4

Related Questions