Showing "Loading" when download button is running in R server and hidden messages when finishing the task

Viewed 461

I am trying to create a shiny app which can download the files from the database but the querying time is very long so I want to let the user know that after they press the button, the web browser shows "loading to the user" and after finished download, "loading" will be hidden.

This is my code:

if (interactive()) {
  
  library(shiny)
  library(shinyWidgets)
  
  ui <- fluidPage(
    downloadBttn(
      outputId = "downloadData",
      style = "bordered",
      color = "primary"
    )
  )
  
  server <- function(input, output, session) {
    data_xi <- data.frame(s = c(1:3),r = c(4:6), x =c(19:21))
    
    observeEvent(input$downloadData, {
      showModal(modalDialog("Loading", footer=NULL))
      
      filename = function() {
        paste('data-', Sys.Date(), '.csv', sep='')
      }
      
      content = function(file) {
        write_xlsx(data_xi,file)
      }
      
      removeModal()
    })
  }
  shinyApp(ui, server)
  
}
1 Answers

Maybe something like this:

library(shiny)

ui <- fluidPage(
  downloadBttn(
    outputId = "downloadData",
    style = "bordered",
    color = "primary"
  )
)

server <- function(input, output, session) {
  data_xi <- data.frame(s = c(1:3),r = c(4:6), x =c(19:21))
  
  output$downloadData <- downloadHandler(
    filename = function() {
      paste('data-', Sys.Date(), '.csv', sep='')
    },
    content = function(file) {
      showModal(modalDialog("Loading", footer=NULL))
      on.exit(removeModal())
      write.csv(data_xi,file)
    }
  )
}

shinyApp(ui,server)
Related