0

Help please! I need to get the value of actionButton current and the one before it was clicked. Please see the code below. At the start both numbers ("click_new" and "click_old") are at 0 but after first click on actionButton I want the current number of clicks go to 1 but the previous number of clicks stay at 0. After the next click the current number of clicks goes to 2 and the previous to 1 and so on... I know that this is, probably, trivial but for the life of me I do not know how to do it. The code is wrong, I know... Please help...

library(shiny)

ui <- fluidPage(
  sidebarPanel(
    actionButton("button", "Button 1")
  ),
  print("Current number of action button clicks"),
  textOutput("click_new"),
  print("Previous number of action button clicks"),
  textOutput("click_old")
)

server <- function(input, output, session) {
  
  click <- reactiveVal(0)
  
  output$click_new <- renderText(click())
  observeEvent(input$button, click(click() + 1))

# I have tried this:
#   observeEvent(input$button, click(click() - 1))
# but it doesnt work

  output$click_old <- reactive({
    as.numeric(input$button)
  })
}

shinyApp(ui, server)

Thank you in advance!!!!

stefan
  • 90,330
  • 6
  • 25
  • 51
AussieAndy
  • 101
  • 2
  • 11

1 Answers1

1

One option would be to use two reactiveVal or a reactiveValues as I do below to store both the new and the old state of the button:

library(shiny)

ui <- fluidPage(
  sidebarPanel(
    actionButton("button", "Button 1")
  ),
  print("Current number of action button clicks"),
  textOutput("click_new"),
  print("Previous number of action button clicks"),
  textOutput("click_old")
)

server <- function(input, output, session) {
  click <- reactiveValues(old = 0, new = 0)

  observeEvent(input$button, {
    click$old <- click$new
    click$new <- click$new + 1
  })

  output$click_old <- renderText(click$old)
  output$click_new <- renderText(click$new)
}

shinyApp(ui, server)

enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51