Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resetting fileInput in Shiny App

Tags:

r

shiny

shinyjs

I have been trying for a long time to reset fileInput in a Shiny app and read solutions to similar problems, but my problem still persists. Most solutions ultimately lead to using Dean Attali's brilliant shinyjs package and the reset() function therein. Here's what my code looks like after following these instructions:

library(shiny)
library(shinyjs) 
library(xlsx) 
library(tidyverse) 

ui <- fluidPage(
  useShinyjs(),
  fileInput('inFile', 'Choose file'),
  actionButton('reset', 'Reset'),
  radioButtons("type","Choose file type",choices = c('csv','xls')),
  tableOutput('tbl')
)

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

  rv <- reactiveValues(data = NULL)

  observe({
    req(input$inFile)
    if(input$type=='csv'){
      rv$data <- read.csv(input$inFile$datapath)
    }
    if(input$type=='xls'){
      rv$data <- read_excel(input$inFile$datapath)
    }

  })

  observeEvent(input$reset, {
    rv$data <- NULL
    reset('inFile')
  })

  output$tbl <- renderTable({
    rv$data
  })
}

shinyApp(ui, server)

I initially select the csv option and am able to load a csv file. Now when I press the reset button, it clears the data. As soon as I select the xls option, I get an error:

Listening on http://127.0.0.1:4135
Warning: Error in : Unknown file extension: csv

Which makes me believe that input$inFile$datapath still contains the pathname of the csv file that I selected earlier. I have run out of ideas on how to solve this problem and would greatly appreciate some help please.

like image 472
Dhiraj Avatar asked Jan 29 '23 11:01

Dhiraj


1 Answers

Ideally fileInput would properly reset, but you can do this as a workaround. Add an explicit flag variable (rv$clear) to indicate whether you're in cleared state, and toggle that on and off in high-priority observers when reset and upload occur, respectively.

library(shiny)
library(shinyjs) 
library(xlsx) 
library(tidyverse) 

ui <- fluidPage(
  useShinyjs(),
  fileInput('inFile', 'Choose file'),
  actionButton('reset', 'Reset'),
  radioButtons("type","Choose file type",choices = c('csv','xls')),
  tableOutput('tbl')
)

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

  rv <- reactiveValues(
    data = NULL,
    clear = FALSE
  )

  observe({
    req(input$inFile)
    req(!rv$clear)

    if(input$type=='csv'){
      rv$data <- read.csv(input$inFile$datapath)
    }
    if(input$type=='xls'){
      rv$data <- read_excel(input$inFile$datapath)
    }

  })

  observeEvent(input$inFile, {
    rv$clear <- FALSE
  }, priority = 1000)

  observeEvent(input$reset, {
    rv$data <- NULL
    rv$clear <- TRUE
    reset('inFile')
  }, priority = 1000)

  output$tbl <- renderTable({
    rv$data
  })
}

shinyApp(ui, server)
like image 181
Joe Cheng Avatar answered Jan 31 '23 08:01

Joe Cheng