I am working on a shiny app. The server.R contains codes like:
dFt1 <- reactiveValues()
dFt1$dat <- data.frame(loadTransactionData())
...
output$t_tab_1 <- DT::renderDataTable({
DT::datatable(
dFt1$dat
,selection = list(mode = "single")
,options = list(
rownames = TRUE
,pageLength = 10
,order = list(list(2,"desc"),list(1,"asc"))
)
)
})
...
observe({
if (is.null(input$delete) || input$delete == 0){return()}
session$sendCustomMessage(
type = 'jsCode'
,list(value = 'confirm("Are You Sure?");')
)
})
observeEvent(input$deleteConfirmChoice, {
if (input$deleteConfirmChoice == "TRUE") {
x <- input$t_tab_1_rows_selected
deleteTransaction(x)
isolate(dFt1$dat <- dFt1$dat[row.names(dFt1$dat) != x, ])
}
})
deleteTransaction <- function(x) {
qy <- "DELETE FROM Transactions where timestamp = '<t>'"
qy <- gsub("<t>",x,qy)
db <- dbConnect(SQLite(), dbname=systemDatabase)
dbGetQuery(db,qy)
dbDisconnect(db)
}
And of course there is the delete button in the ui.R and a called to javascript confirm box.
The app runs good. I can select a record and delete it. Then I can select another record. But I cannot delete it. The javascript confirm box runs, but clicking Yes does not delete the record. I wonder why it is okay for one time but not the next time.
Here is another approach...
I changed the javascript code passed to session$sendCustomMessage. Clicking the No button returns 0. Clicking the Yes button returns a random number. This I hope will guarantee a different value in two consecutive clicks of the Yes button.
observe({
if (is.null(input$delete) || input$delete == 0){return()}
session$sendCustomMessage(
type = 'jsCode'
,list(value =
'
(function() {
if (confirm("Are you sure?")) {
return Math.random()*3 + 1;
} else {
return 0;
}
})()
'
)
)
})
observeEvent(input$deleteConfirmChoice, {
if (input$deleteConfirmChoice == "TRUE") {
x <- input$t_tab_1_rows_selected
deleteTransaction(x)
isolate(dFt1$dat <- dFt1$dat[row.names(dFt1$dat) != x, ])
}
})
Any other cleaner solution?