Home > Enterprise >  Trivial Shiny question: build a list of names from user input
Trivial Shiny question: build a list of names from user input

Time:12-19

Shiny newbie here, struggling with a trivial problem.

Goal: Build a list of names from user input. Each time the user enters a name and clicks Save, append that name to a character vector of names, and update the output with the new contents of that vector.

Problem: Every time they click Save, the character vector has been reinitialized to an empty vector, so the first name is gone, and the new name they entered becomes the only contents of the vector.

ui <- fluidPage(
  fluidRow(
    textInput("name", "Name:"),
    actionButton("btnSave", "Save")
  ),
  fluidRow(
    h5("Output:"),
    verbatimTextOutput("out")
  )
)

server <- function(input, output, session) {
  nameList <- as.character(NULL)
  
  observeEvent(input$btnSave, {
    
    newList <- append(nameList, isolate(input$name))

    nameList <- reactive(newList)
    output$out <- renderPrint(nameList())
  })
}

CodePudding user response:

It looks like you need to have 2 things:

  1. rename newList to nameList.
  2. Within observeEvent give nameList a global assignment (<<-)
ui <- fluidPage(
  fluidRow(
    textInput("name", "Name:"),
    actionButton("btnSave", "Save")
  ),
  fluidRow(
    h5("Output:"),
    verbatimTextOutput("out")
  )
)

server <- function(input, output, session) {
  nameList <- as.character(NULL)
  
  observeEvent(input$btnSave, {
    
    nameList <<- append(nameList, isolate(input$name))
    nameListReactive <- reactive(nameList)
    output$out <- renderPrint(nameListReactive())
  })
}

shiny::shinyApp(ui,server)

CodePudding user response:

library(shiny)
ui <- fluidPage(
  fluidRow(
    textInput("name", "Name:"),
    actionButton("btnSave", "Save")
  ),
  fluidRow(
    h5("Output:"),
    verbatimTextOutput("out")
  )
)

server <- function(input, output, session) {
  
  nameList <- reactiveVal()
  
  observeEvent(input$btnSave, {
    nameList(append(nameList(), input$name))
  })
  
  output$out <- renderPrint(nameList())
  
}

shinyApp(ui = ui, server = server)
  • Related