Galina Polishchuk
Galina Polishchuk

Reputation: 602

Shinyalerts: How do I know whether user pressed OK or Cancel?

I am creating an application that allows user to delete some information. However instead of just deleting it right away, I would like to be sure that the file being deleted is a correct file. I came across the shinyalerts package that allows to to display "are you sure?" popup. However, how do I know what user selected and pass it on to shiny?

library(shiny)
library(shinyalert)

shinyApp(
  ui = fluidPage(
    useShinyalert(),  # Set up shinyalert
    actionButton("btn", "Delete")
  ),
  server = function(input, output) {
    observeEvent(input$btn, {
      shinyalert(
        title = "Are you sure you want to delete this file?",
        text = "You will not be able to recover this imaginary file!",
        type = "warning",
        showCancelButton = TRUE,
        confirmButtonCol = '#DD6B55',
        confirmButtonText = 'Yes, delete it!'
      )

    })
  }
)

Upvotes: 3

Views: 2007

Answers (1)

Tonio Liebrand
Tonio Liebrand

Reputation: 17719

You can use callbackR() e.g. store it in a reactiveValue() (named global): callbackR = function(x) global$response <- x.

The full app would read:

library(shiny)
library(shinyalert)

shinyApp(
  ui = fluidPage(
    useShinyalert(),  # Set up shinyalert
    actionButton("btn", "Delete")
  ),
  server = function(input, output) {
    global <- reactiveValues(response = FALSE)

    observeEvent(input$btn, {
      shinyalert(
        title = "Are you sure you want to delete this file?",
        callbackR = function(x) {
          global$response <- x
        },
        text = "You will not be able to recover this imaginary file!",
        type = "warning",
        showCancelButton = TRUE,
        confirmButtonCol = '#DD6B55',
        confirmButtonText = 'Yes, delete it!'
      )
      print(global$response)
    })
  }
)

Upvotes: 9

Related Questions