How to count downloads?

My question is closely related to that one.

I need to add a counter for downloads. So I use a reactive value that I want to set inside the 'content' argument of the downloadHandler function

An example:

library(shiny)
ui <- fluidPage(
  downloadButton("downloadData", "Download"),
  actionButton("trig", "get number")
)

server <- function(input, output) {
  data <- mtcars
  rnDownloads <- reactiveValues(n=0)

  observe(print(rnDownloads$n))

  observeEvent(input$trig, {
    print(paste("number of downloads:", rnDownloads$n))
  })
  
  output$downloadData <- downloadHandler(
    filename = function() {
      paste("data-", Sys.Date(), ".csv", sep="")
    },
    content = function(file) {
      rnDownloads$n <- rnDownloads$n + 1
      write.csv(data, file)
    }
  )
}

shinyApp(ui, server)

I don't know whether it's a bug, but it does not work as I expected: the only way to update the value of the reactiveValue rnDownloads$n is to click on the actionButton.

I can't tell if this is a bug or not, but a guy in this post offers a solution using Javascript to count button clicks. I hope this is helpful....!!!!

This is a bug in Shiny. Can you file it on our GitHub repo, with a link to this thread? The problem is that hitting that URL does not cause Shiny to "flush" the session. It should be an easy fix--thanks for the report.

If you must have this working now, you can add a dummy observer that does nothing but cause the session to flush. You can do this by putting this anywhere in your server function:

observe({
  invalidateLater(500)
})