Shiny app enigma

Hello,

Launch the app below. Type "xxx" in the text input, then click the first button (in the table). Now type "yyy" in the text input and click the second button. Then the second observer prints "xxx ~~~~ yyy". Why "xxx"? Enjoy.

library(shiny)
library(DT)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel = sidebarPanel(
      textInput("txt", "Type text"),
    ),
    mainPanel = mainPanel(
      DTOutput("dtable")
    )
  )
)

server <- function(input, output, session) {
  
  output[["dtable"]] <- renderDT(
    data.frame(
      "content" = rep(input[["txt"]], 5L),
      "buttons" = unlist(lapply(1:5, function(i){
        as.character(
          tags$button(
            id = paste0("ab", i), 
            onclick = "Shiny.setInputValue(this.id, 42, {priority: 'event'})",
            paste0("ab", i)
          )
        )
      }))
    ),
    escape = FALSE
  )
  
  abObserver <- function(i, message = " is greeting you"){
    print(paste("observeEvent is being created:", i))
    observeEvent(input[[paste0("ab", i)]], {
      print(input[[paste0("ab",i)]])
      print(paste0(
        "observing ab", i, " with message: ", message, " ~~~~~ ", input[["txt"]]
      ))
    })
  }

  observerlist <- lapply(1:5, abObserver, message = input[["txt"]])

}

shinyApp(ui, server)
1 Like

Hello,

Launch the app below. Type "yyy" in the text input and then click on the first button (in the table). Then the observer prints "yyy ~~~~ yyy". Now type "zzz" and click on the second button. Then "yyy ~~~~ zzz" is printed. Why "yyy"?

library(shiny)
library(DT)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel = sidebarPanel(
      textInput("txt", "Type text"),
    ),
    mainPanel = mainPanel(
      DTOutput("dtable")
    )
  )
)

server <- function(input, output, session) {
  
  output[["dtable"]] <- renderDT(
    data.frame(
      "content" = rep(input[["txt"]], 5L),
      "buttons" = unlist(lapply(1:5, function(i){
        as.character(
          tags$button(
            id = paste0("ab", i), 
            onclick = "Shiny.setInputValue(this.id, 42, {priority: 'event'})",
            paste0("ab", i)
          )
        )
      }))
    ),
    escape = FALSE
  )
  
  abObserver <- function(i, message = " is greeting you"){
    print(paste("observeEvent is being created:", i))
    observeEvent(input[[paste0("ab", i)]], {
      print(input[[paste0("ab",i)]])
      print(paste0(
        "observing ab", i, " with message: ", message, " ~~~~~ ", input[["txt"]]
      ))
    })
  }

  observerlist <- lapply(1:5, abObserver, message = input[["txt"]])

}

shinyApp(ui, server)

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.