user1981275
user1981275

Reputation: 13372

R shiny reactive list of files

New to shiny, I want my app to display all files in a directory, and make the list update every time a file is added or removed. I see this is possible with reactivePoll, so I put this in my server:

server <- function(input, output, session) {

    has.new.files <- function() {
        length(list.files())
    }
    get.files <- function() {
        list.files()
    }
    output$files <- renderText(reactivePoll(10, session, checkFunc=has.new.files, valueFunc=get.files))    
}

However, I don't know how I can access the character vector containing my files within my ui. I also doubt that renderText in my server is the right choice. Here is my ui (non-reactive, just reads file list once):

ui <- fluidPage(

    ## How to access the files from server function ??
    selectInput("file", "Choose file", list.files())
)

Thus, I just don't know hot to access the data, could anyone point me in the right direction?

Upvotes: 3

Views: 2106

Answers (1)

Florian
Florian

Reputation: 25385

You could try this:

server <- function(input, output, session) {

  has.new.files <- function() {
    unique(list.files())
  }
  get.files <- function() {
    list.files()
  }

  # store as a reactive instead of output
  my_files <- reactivePoll(10, session, checkFunc=has.new.files, valueFunc=get.files)

  # any time the reactive changes, update the selectInput
  observeEvent(my_files(),ignoreInit = T,ignoreNULL = T, {
    print(my_files())
    updateSelectInput(session, 'file',choices = my_files())
  })

}


ui <- fluidPage(
  selectInput("file", "Choose file", list.files())
)

shinyApp(ui,server)

It updates the selectInput any time a file is added, deleted or renamed. If you only want it to change if a file is added, you can replace the has.new.files function back with your own. Hope this helps!

Upvotes: 4

Related Questions