I have a Shiny app that allows the user to load a csv and then plot the data.
I then have some custom functions to create different UI elements, that are passed into the server, for example:
GroupByUI <- function(id,
data,
label = 'Group By',
selected = 'All',
None = FALSE,
All = TRUE) {
renderUI({
xsecs <- data %>%
select_if(is.character) %>%
names()
if (None) {
xsecs <- c('None', xsecs)
}
if (All == FALSE) {
xsecs <- xsecs[-which(xsecs == 'All')]
selectInput(inputId = paste0('groupby_', id),
label = label,
choices = as.list(xsecs),
selected = as.list(xsecs)[1])
} else {
selectInput(inputId = paste0('groupby_', id),
label = label,
choices = as.list(xsecs),
selected = selected)
}
})
}
and in the server I have:
output$GroupBy_Area <- GroupByUI(
id = "area",
data = dataFlt()
)
and this works when I load a first csv (e.g. the Group By selectInput
is updated the correct variable names).
For context, dataFlt() is a reactive
and it’s set to NULL and updates every time I load a new/different csv.
dataFlt <- reactive({
req(uploadedData$data)
datafl <- uploadedData$data
})
The problem that I have is, that if I have loaded a csv, plotted the data and then I change the csv that I load (e.g. I change the data I want to plot, variables’ names change), the options in the Group By selectInput
do not update accordingly UNLESS I move the renderUI
directly to the server:
output$GroupBy_Area <- renderUI({
req(dataFlt())
GroupByUI(id = "area",
data = dataFlt())
})
and I remove the renderUI
from the function:
GroupByUI <- function(id, data, label = 'Group By', selected = 'All', None = FALSE, All = TRUE) {
xsecs <- data %>%
select_if(is.character) %>%
names()
if (None) {
xsecs <- c('None', xsecs)
}
if (All == FALSE) {
xsecs <- xsecs[-which(xsecs == 'All')]
selectInput(inputId = paste0('groupby_', id),
label = label,
choices = as.list(xsecs),
selected = as.list(xsecs)[1])
} else {
selectInput(inputId = paste0('groupby_', id),
label = label,
choices = as.list(xsecs),
selected = selected)
}
}
With this latest code (moving the renderUI
directly to the server), it works every time I change the data I load.
What I don’t understand is why. What’s the difference? And why do the original code works the first time?