Catelinn Xiao
Catelinn Xiao

Reputation: 141

reactiveValues cannot be used to render output

I'm developing a shiny app using reactive value, of course. However, I'd like to explore the use of reactiveValues to test my understanding of the concept. My design is to create a dt container of reactive values, e.g. data, cols, rows; so that I can save shiny input$file uploaded data to dt$data; also I'd use checkboxGroupInput to display the columns of the data, which is saved as dt$cols, and let users to select columns and then render data table of dt$data[dt$cols]. Here's the code I used:

dt <- reactiveValues()
observeEvent(input$uploadbutton, {

       file <- input$file
       req(input$file)
       f <- read.csv(file$datapath, header = TRUE)
       dt$data <- f

       # get the col names of the dataset and assign them to a list
       cols <- mapply(list, names(dt$data))

       # update columns ui under columnscontrol div
       updateCheckboxGroupInput(session, "columns", "Select Columns:", choices = cols, selected = cols)
})

observeEvent(input$columns, { dt$cols <- input$columns  })

output$datatbl <- DT::renderDataTable(
   dt$data[dt$cols], rownames = FALSE,
   # column filter on the top
   filter = 'top', server = TRUE,
   # autoWidth
   options = list(autoWidth = TRUE)
)

The code didn't work, I was thrown with the error of "undefined columns" when dt$data[dt$cols] is called. However, the above works fine if I only use reactive value dt2 <- eventReactive(input$columns, { f <- dt$data[input$columns], f }) and then call dt2() in renderDataTable(). I wonder what's wrong with the use of the variables in reactiveValues.

Upvotes: 0

Views: 466

Answers (1)

HubertL
HubertL

Reputation: 19544

When you upload the file, the instruction dt$data <- f will then trigger the renderDataTable which uses dt$data. This happens before dt$cols <- input$columns is called therefore dt$colsis NULL and dt$data[dt$cols] throws an error.

You can try with isolate :

isolate(dt$data)[dt$cols] 

Upvotes: 1

Related Questions