Closed obenno closed 2 years ago
Your code is not a minimal reprex. A minimal reprex to test whether toggleState
works is as follows:
library(shiny)
library(shinyjs)
ui <- fluidPage(
shinyjs::useShinyjs(),
actionButton("go", "Generate File"),
downloadButton("download", "Download")
)
server <- function(input, output, session) {
observe({
# only enable the button every 3 clicks
toggleState(id = "download", input$go %% 3 == 2)
})
}
shinyApp(ui, server)
As you can see above, toggleState works. The issue you're having stems from incorrect code, but it's not a bug in shiny js. If you cannot solve the problem, I suggest asking for help online or reaching out to me for paid help
Thanks a lot for the confirmation, I will check it myself.
From just reading your code, without testing it myself, I think your issue here is misunderstanding how reactivity works. The observer around toggleState only gets triggered even the filename input is changed. So if you click the button and the file gets created, the observer doesn't fire. Reactivity is indeed the hardest thing to learn in shiny
Thanks for the hints, that really helps!
I've just found a solution based on shiny's reactivePoll function. In case someone else facing the same problem, just post the solution here. Thanks again!
library(shiny)
library(shinyjs)
ui <- fluidPage(
shinyjs::useShinyjs(),
div(
textInput("filename", "File Name"),
actionButton("go", "Generate File"),
downloadButton("download", "Download")
)
)
server <- function(input, output, session) {
data <- reactivePoll(1000, session,
## This function returns the time stamp of data file
checkFunc = function() {
datafile <- paste0(tempdir(), "/", input$filename, ".txt")
if (file.exists(datafile))
file.info(datafile)$mtime[1]
else
""
},
valueFunc = function() {
## do nothing
}
)
observe({
toggleState(id = "download",
data()
)
})
observeEvent(input$go, {
req(input$filename)
## create file
system(paste0("echo OK > ", tempdir(), "/", input$filename, ".txt"))
})
output$download <- downloadHandler(
filename = function() {
paste('data-', Sys.Date(), '.tgz', sep='')
},
content = function(file){
system(paste0("tar cvzf ",
file, " ",
tempdir(), "/", input$filename, ".txt"))
}
)
}
shinyApp(ui, server)
Hi @daattali ,
I used
toggleState
for a downloadButton to check whether the file required exists. The downloadButton is disabled as expected, but after the file is ready, the button will not be enabled immediately. I'm not quite sure if this is related to{shinyjs}
or I ust wrote the code in a wrong way.Please kindly find a reproducible example below:
sessionInfo:
Many Thanks, obenno