5

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)
Simon
  • 675
  • 1
  • 6
  • 15
  • "At the moment clicking the download button before 5 secs returns the default html file and then after 5 secs it behaves as expected." I would be *so* interested in seeing code that reproduces this. I am seeing this problem in my app, and I don't really have a clue why it happens, so I don't like to apply some random workaround from the internet only to see it break at some point in time in the future ;) I imagine that simply adding a `Sys.sleep(5)` in the `content` function will not lead to this behavior - I have a minute-long process preparing a download and that is working most of the time. – bers Mar 30 '22 at 18:41

1 Answers1

2

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.

DeanAttali
  • 25,268
  • 10
  • 92
  • 118
  • Thanks for the response and thank you for the excellent package. I'll read more about the package's other functions. – Simon May 27 '20 at 11:00