Reputation: 79
I'm new to R and Shiny and I'm trying to work out how to allow the user to add new 'choices' to a selection list one at a time. e.g. if the user uploads datasets one at a time, the names of all the datasets would then be available for selection in the selection list.
I have done the simple version (see below), where a user can add a single new 'choice' to the list. But it obviously does not save each new choice when you keep adding new choices.
My attempt at adding more than 1 new choice is also below.
#### Simple working version of adding 1 new choice ####
choices <- c("x", "y", "z")
ui <- fluidPage(
selectizeInput("choices","Choices", choices = choices, multiple = TRUE),
textInput("new_choices", "New choices to add"),
actionButton("add_choices", "Add new choices")
)
server <- function(input, output,session) {
observeEvent(input$add_choices, {
req(input$new_choices)
choices <- c(choices, input$new_choices)
updateSelectizeInput(session, "choices", choices = choices)
})
}
shinyApp(ui = ui, server = server)
#### Not working version of sequentially adding new choices ####
choices <- c("x", "y", "z")
ui <- fluidPage(
selectizeInput("choices","Choices", choices = choices, multiple = TRUE),
textInput("new_choices", "New choices to add"),
actionButton("add_choices", "Add new choices")
)
server <- function(input, output,session) {
temp <- reactive({
choices
})
update_choices <- function() {
temp <- reactive({
c(temp, input$new_choices)
})
return(temp)
}
observeEvent(input$add_choices, {
req(input$new_choices)
temp <- update_choices()
updateSelectizeInput(session, "choices", choices = temp)
})
}
shinyApp(ui = ui, server = server)
The non-working code results in this: Warning: Error in as.vector: cannot coerce type 'closure' to vector of type 'list' [No stack trace available]
Upvotes: 2
Views: 76
Reputation: 973
Just add a reactive value with the choices
library(shiny)
ui <- fluidPage(
selectizeInput("choices","Choices", choices = c(), multiple = TRUE),
textInput("new_choices", "New choices to add"),
actionButton("add_choices", "Add new choices")
)
server <- function(input, output,session) {
values = reactiveValues()
values$current_choices = c("x", "y", "z")
observeEvent(input$add_choices, {
req(input$new_choices)
values$current_choices <- c(values$current_choices, input$new_choices)
})
observe({
updateSelectizeInput(session, "choices", choices = values$current_choices, selected = input$choices)
})
}
shinyApp(ui = ui, server = server)
Upvotes: 1