Damata Damata - 12 days ago 7
R Question

How to update UI on file change

Hello I'm building a shinydashboard using several excel files.

I inserted links to these files in the footer of the box and I want to refresh the shinydashboard when changing something in my excel file.
I don't want to run the whole R code each time.

How can I re-render the Output once the file content changes?

Here an example:

sidebar <- dashboardSidebar(
sidebarMenu( menuItem("Hello", tabName = "Hello", icon = icon("dashboard"))
))

body <- dashboardBody(
tabItems(

tabItem(tabName = "Hello",


box(title = "my file",
footer = a("df.xlsx", href="df.xlsx" ) ,
DT::dataTableOutput("df1"),style = "font-size: 100%; overflow: auto;",
width = 12, hight = NULL, solidHeader = TRUE, collapsible = TRUE, collapsed = TRUE, status = "primary")
)))


ui <- dashboardPage(
dashboardHeader(title = "My Dashboard"),
sidebar,
body)


server <- function(input, output) {
output$df1 <- renderDataTable({
df <- read_excel("df.xlsx")
DT::datatable(df, escape = FALSE, rownames=FALSE,class = "cell-border",
options =list(bSort = FALSE, paging = FALSE, info = FALSE)
)
})
}



shinyApp(ui, server)

Answer

To monitor the change in a file you could use the cheksum of the file like this:

library(shiny)
library(digest)

# Create data to read
write.csv(file="~/iris.csv",iris)

shinyApp(ui=shinyUI(
  fluidPage(
    sidebarLayout(
      sidebarPanel(
        textInput("path","Enter path: "),
        actionButton("readFile","Read File"),
        tags$hr()
      ),
      mainPanel(
        tableOutput('contents')
      )))
),
server = shinyServer(function(input,output,session){
  file <- reactiveValues(path=NULL,md5=NULL,rendered=FALSE)

  # Read file once button is pressed
  observeEvent(input$readFile,{
    if ( !file.exists(input$path) ){
      print("No such file")
      return(NULL)
    }
    tryCatch({
      read.csv(input$path)
      file$path <- input$path
      file$md5  <- digest(file$path,algo="md5",file=TRUE)
      file$rendered <- FALSE
    },
    error = function(e) print(paste0('Error: ',e)) )
  })

  observe({
    invalidateLater(1000,session)
    print('check')

    if (is.null(file$path)) return(NULL)

    f   <- read.csv(file$path)
    # Calculate ckeksum
    md5 <- digest(file$path,algo="md5",file=TRUE)

    # If no change in cheksum, do nothing
    if (file$md5 == md5 && file$rendered == TRUE) return(NULL)

    output$contents <- renderTable({

      print('render')
      file$rendered <- TRUE
      f
    })
  })

}))