Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable button in shiny while plot is loading

Tags:

r

shiny

shinyjs

Is it possible to disable a button in shiny while a plot / a reactive element is loading? I know shinyjs can disable and enable input elements, but I don't know how to set up the connection to a loading plot / reactive element. The example is based on the Single-file shiny apps page. I just added a button and the isolated part. Solutions that are not based on shinyjs are also appreciated :)

library(shiny)
server <- function(input, output) {
  output$distPlot <- renderPlot({
    input$button

    isolate(
      hist(rnorm(input$obs), col = 'darkgray', border = 'white')
    )
  })
}

ui <- fluidPage(
  shinyjs::useShinyjs(),
  sidebarLayout(
    sidebarPanel(
      sliderInput("obs", "Number of observations:", min = 10, max = 500, value = 100),
      actionButton("button", "OK!")
    ),
    mainPanel(plotOutput("distPlot"))
  )
)

shinyApp(ui = ui, server = server)
like image 795
Felix Grossmann Avatar asked May 12 '17 15:05

Felix Grossmann


Video Answer


2 Answers

Something like this?

library(shiny)
library(shinyjs)
server <- function(input, output) {

  PlotData <- eventReactive(input$button,{
    disable("button") 
    Sys.sleep(2)
    hist(rnorm(input$obs), col = 'darkgray', border = 'white')
    enable("button") 
  })

  output$distPlot <- renderPlot({
    PlotData()
  })
}

ui <- fluidPage(
  shinyjs::useShinyjs(),
  sidebarLayout(
    sidebarPanel(
      sliderInput("obs", "Number of observations:", min = 10, max = 1000, value = 2000),
      actionButton("button", "OK!")
    ),
    mainPanel(plotOutput("distPlot"))
  )
)

shinyApp(ui = ui, server = server)
like image 52
Pork Chop Avatar answered Sep 30 '22 17:09

Pork Chop


In the following way you don't have to set a time. The button is disabled only during the calculation.

library(shiny)

js <- "
$(document).ready(function() {
  $('#distPlot').on('shiny:recalculating', function() {
    $('button').prop('disabled', true);
    $('button').css('color', 'red');
  });
  $('#distPlot').on('shiny:recalculated', function() {
    $('button').prop('disabled', false);
    $('button').css('color', 'black');
});
});
"

server <- function(input, output) {

  output$distPlot <- renderPlot({
    hist(rnorm(input$obs), col = 'darkgray', border = 'white')
  })
}

ui <- fluidPage(
  tags$head(tags$script(HTML(js))),
  sidebarLayout(
    sidebarPanel(
      sliderInput("obs", "Number of observations:", min = 10000, max = 100000, value = 20000),
      actionButton("button", "OK!")
    ),
    mainPanel(plotOutput("distPlot"))
  )
)

shinyApp(ui = ui, server = server)
like image 22
Stéphane Laurent Avatar answered Sep 30 '22 17:09

Stéphane Laurent