Home > OS >  How to have sequential Modal dialogs in Shiny
How to have sequential Modal dialogs in Shiny

Time:01-12

I need a shiny app to do the following:

  1. The user clicks a button
  2. N pop-ups appear to the user asking for input
  3. Then the user downloads the information displayed in the app with a download button

I've been able to achieve points 1 & 2, however I haven't been able to get to 3 because of the fact that the user inputs are reactive values. Here is a sample of code that almost works:

library(shiny)
library(shinyalert)

test <- c("C", "D", "F")
NUM_MODALS <- length(test)

ui <- fluidPage(
  shinyalert::useShinyalert(),
  actionButton("show", "Show modal dialog"),
  lapply(seq(NUM_MODALS), function(id) {
    div(id, ":", textOutput(paste0("modal", id), inline = TRUE))
  }),
  downloadButton("downloadData", "Download")
)

server <- function(input, output) {
  
  observeEvent(input$show, {
    for(id in 1:NUM_MODALS){
      shinyalert::shinyalert(
        type = "input",
        text = paste("¿Cuál es la industria de la siguiente empresa?:", test[id]),
        inputPlaceholder = "Cuidado con mayúsculas/minúsculas",
        inputId = paste0("modal", id)
      )
    }
  })
  
  lapply(seq(NUM_MODALS), function(id) {
    output[[paste0("modal", id)]] <- renderText({paste(test[id],input[[paste0("modal", id)]])})
  })
  export <- reactive(c(input$modal1, input$modal2, input$modal3))
  export2 <- isolate(export)
  print(export2)
  #browser()
  output$downloadData <- downloadHandler(
    
    filename = function() {
      paste('data-', Sys.Date(), '.csv', sep='')
    },
    content = function(filesillo) {
      fs <- c()
      tmpdir <- tempdir()
      setwd(tempdir())
      path <- paste("prueba.txt", sep = "")
      fs <- c(fs, path)
      write.csv(export2, filesillo)
      
    }
  )
}

shinyApp(ui = ui, server = server)

CodePudding user response:

Instead of the inputs being assigned as a reactive, you can assign to reactiveValues in an observe.

  export <- reactiveValues(
    dat = NULL
  )
  
  observe({
    export$dat <- dplyr::bind_rows(
      modal1 = input$modal1,
      modal2 = input$modal2,
      modal3 = input$modal3
    )
  })
  # export <- reactive(c(input$modal1, input$modal2, input$modal3))
  # export2 <- isolate(export)
  # print(export2)
  #browser()

Then in your downloadHandler

      #write.csv(export2, filesillo)
      write.csv(export$dat, filesillo)

This will output a csv with modal inputs as columns

  • Related