Simon
Simon

Reputation: 685

Shiny downloadHandler wait for data to be ready

The data in my shiny application takes a few seconds to be processed. I have a download button and I would like it to be either unclickable until the data are prepared or have the download handler wait until prepared. At the moment clicking the download button before 5 secs returns the default html file and then after 5 secs it behaves as expected.

My current solution is to use `shinyjs::hide/show. I’ve shown this below.

Is this best practice? Also, why the shinyjs::useShiny() at the start? It seems unique to that package.

ui <- fluidPage(
shinyjs::useShiny(),
  shinyjs::hidden(downloadButton("downloadData", "Download"))
)

server <- function(input, output) {
   # Our dataset
  data <- mtcars

if(is.null(mtcars)){shinyjs::hide(“downloadData”)}
else{shinyjs::show(“downloadData”)}

   output$downloadData <- downloadHandler(
     filename = function() {
      paste("data-", Sys.Date(), ".csv", sep="")
     },
     content = function(file) {
      write.csv(data, file)}
  )
}

shinyApp(ui, server)

Upvotes: 5

Views: 1037

Answers (1)

DeanAttali
DeanAttali

Reputation: 26363

What you describe is perfectly reasonable and has been suggested on stackoverflow in the past. You can also use disable/enable instead of hide/show, whatever you feel is a better user experience.

The useShinyjs() is required to set up all the R <--> JavaScript communication that is happening. Without it, when you try to call a shinyjs function from the server, nothing will happen because the UI didn't get initialized with the javascript. Some other pacakges have also adopted this pattern since I made shinyjs, especially packages that also deal with javascript.

Upvotes: 3

Related Questions