nd091680
nd091680

Reputation: 605

Enable/Disable action button if a reactive object that lists files in folder is not NULL

I have a Shiny application where there is an action button that must be disabled (using the package shinyjs) in the case that a reactive object, created in the server and used to list files in different folders, is not NULL, i.e., if there are files in the folders.

For this example, suppose you have 3 folders on your Desktop that are named "url_1", "url_2", and "url_3". In the app, you can select these folders through a radioButton() placed in the app. Also, suppose that only one folder ("url_1") contains a file (you can easily put a .txt file in it). Below please find a reproducible example:

# LIBRARIES
library(shiny)
library(shinyjs)

# UI
ui <- fluidPage(
  
  useShinyjs(),
  
  fluidRow(
    
    column(width = 1,
           
           radioButtons(inputId = "urls",
                        choices = c("URL 1" = "url_1",
                                    "URL 2" = "url_2",
                                    "URL 3" = "url_3"),
                        label = "Matches")
           
    ),
    
    column(width = 1,
           
           actionButton(inputId = "test_url_1",
                        label = "TEST")
           
    )
    
  )
  
)

# SERVER
server <- function(input, output, session) {
  
  # Create a reactive object that list files in each folder
  files_available <- reactive({
    
    req(input$urls)
    
    files <- list.files(path = paste0("~/desktop/", input$urls))
    
    if (length(x = files) > 0) {return(files)} else {return(NULL)}
    
  })
  
  # Disable the action button if the above reactive object is not NULL
  observe({
    
    if (!is.null(x = files_available())) {
      
      shinyjs::disable(id = paste0("test_", input$urls))
      
    } else {
      
      shinyjs::enable(id = paste0("test_", input$urls))
      
    }
    
  })
  
}

# RUN APP
shinyApp(ui = ui, server = server)

When the reactive variable files_available is placed within the observer, I don't get the required behavior because the button "TEST" is always disabled.

Upvotes: 0

Views: 48

Answers (0)

Related Questions