Ketty
Ketty

Reputation: 851

How to automatically trigger an action button in R Shiny

I'd like to run the action button automatically when users open/land on 'tab1'. Therefore, instead of clicking the Refresh button to view the date, I'd like to have the date printed automatically. Is there a way to do this? My real code is more complicated that this simple example. However, it demonstrates what I'd like to do. Thank you!

library(shiny)

ui <- fluidPage(
  shiny::tabPanel(value = 'tab1', title = 'Data page',
                  br(),
                  shiny::actionButton("btn", "Refresh!"),
                  br(),
                  shiny::verbatimTextOutput("out")
  )
)

server <- function(input, output, session) {
   curr_date <- shiny::eventReactive(input$btn, {
     format(Sys.Date(), "%c")
   })

   output$out <- shiny::renderText({
     print(curr_date())

   })
}

shinyApp(ui, server)

Upvotes: 2

Views: 5573

Answers (2)

St&#233;phane Laurent
St&#233;phane Laurent

Reputation: 84519

You can make curr_date reactive to the tabset:

library(shiny)

ui <- fluidPage(
  tabsetPanel(
    tabPanel(value = 'tab1', title = 'Data page',
             br(),
             actionButton("btn", "Refresh!"),
             br(),
             verbatimTextOutput("out")
    ),
    tabPanel(value = 'tab2', title = 'Other tab'),
    id = "tabset"
  )
)

server <- function(input, output, session) {
  curr_date <- eventReactive(list(input$btn, input$tabset), {
    req(input$tabset == 'tab1')
    format(Sys.time(), "%c")
  })

  output$out <- renderText({
    print(curr_date())
  })
}

shinyApp(ui, server)

Upvotes: 2

annhak
annhak

Reputation: 662

You should use reactiveValues() and observeEvent() for this. Inside server function:

server <- function(input, output, session) {

  text_out <- reactiveValues(date = format(Sys.Date(), "%c"))

  observeEvent(input$btn, {
    text_out$date <- "something else"
  })

  output$out <- renderText({
     print(text_out$date)
}

Upvotes: 0

Related Questions