Adrarc
Adrarc

Reputation: 151

How to debounce multiple inputs using a loop?

I have created lots of text inputs using a loop:

lapply(1:5, function(x){textInput(paste0('text',x), label = '')}) 

I have now input$text1, input$text2, input$text3 etc...
How can I debounce them using a loop?
The idea is to now have objects named debounced_text1,debounced_text2, etc..

Below does not work:

lapply(1:5, function(x){
  
  assign(paste0('debounced_text',x),debounce(r = input[[paste0('text',x)]], millis = 1000), envir = .GlobalEnv) 
  
})

I have also tried using get()

debounce(r = get(paste0('input$text',x), millis = 1000) 

but using get() that way does not work.
Thank you in advance!

Upvotes: 1

Views: 308

Answers (1)

ismirsehregal
ismirsehregal

Reputation: 33550

debounce expects a reactive expression - please check the following.

Debounce each input separately:

library(shiny)

textInputIDs <- paste0('text', 1:5)

ui <- fluidPage(
  lapply(textInputIDs, function(x){textInput(x, label = x)}),
  textOutput("debouncedText")
)

server <- function(input, output, session) {
  lapply(textInputIDs, function(x){assign(paste0("debounced_", x), debounce(r = reactive({input[[x]]}), 1000), envir = .GlobalEnv)})
  
  output$debouncedText <- renderText({
    paste("User input:", debounced_text1(), debounced_text2(), debounced_text3(), debounced_text4(), debounced_text5(), sep = ", ")
  })
}

shinyApp(ui, server)

Another approach is to wrap all inputs in a single reactive which returns a list() and debounce only this reactive.

Debounce bundled inputs:

library(shiny)

textInputIDs <- paste0('text', 1:5)

ui <- fluidPage(
  lapply(textInputIDs, function(x){textInput(x, label = x)}),
  textOutput("debouncedText")
)

server <- function(input, output, session) {
  
  debouncedInputs <- debounce(r = reactive({lapply(textInputIDs, function(x){input[[x]]})}), 1000)
  
  output$debouncedText <- renderText({
    paste("User input:", paste(debouncedInputs(), collapse = ", "))
  })
}

shinyApp(ui, server)

Upvotes: 1

Related Questions