saheed
saheed

Reputation: 394

How to update a character vector from shiny textInput?

I want to add the input text to a vector in a Shiny app every time a button is clicked. This is the example I'm working with:

library(shiny)
ui <- fluidPage(
     textInput(inputId = "inquiry", label = "enter text"),
     actionButton(inputId = "searchButton", label = "Run"),
     verbatimTextOutput("queryList", placeholder = FALSE)
)
server <- function(input, output, session) {
     queryList <- c()
     observeEvent(input$searchButton, {
          queryList[length(queryList)+1] <- input$inquiry
          output$queryList <- renderPrint({
               queryList
          })
     })
}
shinyApp(ui = ui, server = server)

So if "item1" is entered and the button is clicked, then "item2" is entered and the button is clicked again, queryList should look like c("item1", "item2"), but it seems to just be replacing "item1" with "item2". I'm sure I'm missing something very simple...queryList[length(queryList)+1] looks a little strange, but it works in a non-reactive environment.

Upvotes: 2

Views: 556

Answers (1)

f.lechleitner
f.lechleitner

Reputation: 3812

Making queryList reactive fixed it for me:

library(shiny)

ui <- fluidPage(
  textInput(inputId = "inquiry", label = "enter text"),
  actionButton(inputId = "searchButton", label = "Run"),
  verbatimTextOutput("queryList", placeholder = FALSE)
)

server <- function(input, output, session) {
  queryList <- reactiveValues()
  queryList$values <- c()

  observeEvent(input$searchButton, {
    queryList$values[length(queryList$values) + 1] <- input$inquiry
  })

  output$queryList <- renderPrint({
    if (!is.null(queryList$values)) {
      queryList$values
    }
  })
}

shinyApp(ui = ui, server = server)

Upvotes: 3

Related Questions