Batanichek
Batanichek

Reputation: 7871

Save state of input shiny

Is there good way to save state( dont reset ) of shinyinput which generated on server side?

Example

ui=shinyUI(fluidPage(
  selectInput("select","",choices = c(1,2),multiple = T),
  uiOutput("din_ui")
  ))

server=function(input, output,session) {
  output$din_ui=renderUI({
    lapply(input$select,function(i){
      numericInput(inputId = paste0("num_",i),i,"")
    })
  })

}

shinyApp(ui,server)

If i select 1 in select insert some values into num_1 than add 2 in select than num_1 reset to start value.

Upvotes: 5

Views: 667

Answers (2)

Batanichek
Batanichek

Reputation: 7871

Also find other way using insertUI ( shiny version >=14)

ui=shinyUI(fluidPage(
  selectInput("select","",choices = c(1,2),multiple = T),
  div(id="din_2")
)) 

server=function(input, output,session) {
  sel_dat=reactiveValues(sel=NULL)

  observeEvent(input$select,{
    to_add=input$select[!input$select%in%sel_dat$sel]
    for ( i in to_add){
           insertUI(
            selector = '#din_2',
            where = "beforeEnd",
            ui =numericInput(inputId = paste0("num_",i),i,"")
          )
    }
    to_remove=sel_dat$sel[which(!sel_dat$sel %in% input$select)]
    if(length(to_remove)>0){
      removeUI(selector = paste0('div:has(>#num_',to_remove,")"))
    }
    sel_dat$sel=input$select
  },ignoreNULL = FALSE)

}

Upvotes: 0

Eduardo Bergel
Eduardo Bergel

Reputation: 2775

You can read the numericInput value, and set the control value at control init. See code:

library(shiny)

ui=shinyUI(fluidPage(
  selectInput("select","",choices = c(1,2),multiple = T),
  uiOutput("din_ui")
)) 

server=function(input, output,session) {
  output$din_ui=renderUI({

    input$select 

    isolate(
      lapply(X   = input$select, 
             FUN = function(i){ 
               cn <- paste0("num_",i)
               numericInput(inputId = cn,
                            label   = i,
                            value   = ifelse(!is.null(input[[cn]]), input[[cn]], ''))
             }
      )
    )
  })

}

shinyApp(ui,server)

Upvotes: 3

Related Questions