简体   繁体   中英

How to I use a variable from the shiny UI outside of a reactive environment?

Situation : I have one input where you can choose "small" or "big", a csv-file with data and another input, where you can choose from a list from the csv depending on your choice of "small" or "big".

Problem : I cannot find a way to access the variable input$selecter in the updateSelectizeInput function.

Here is my minimal code example which unfortunately does not work:

library(shiny)

ui=fluidPage(
  selectInput('selecter', "Choose ONE Item", choices = c("small","big")),
    selectizeInput('chooser', 'Choose SEVERAL Items', choices = NULL, multiple = TRUE)
)

server=function(input,output,session){
 DatafromMytable=read.csv("mytable.csv", header=TRUE, sep=";")
 # mysubset=subset(DatafromMytable,Size=="big") #
   mysubset=subset(DatafromMytable,Size==input$selecter)
 updateSelectizeInput(session, "chooser", choices = mysubset$Item) 

}

shinyApp(ui, server)

Question : What do I need to change in the line updateSelectizeInput(session, "chooser", choices = mysubset$Item) to make the code work?

You have to make your variable mysubset into a reactive, and then call its value with mysubset() . Also, you need an observer that fires the updateSelectizeInput whenever it sees that mysubset() has changed.

Example below. Note that I have commented out your read.csv statement, and added some sample data to make your example reproducible . Hope this helps!

library(shiny)

ui=fluidPage(
  selectInput('selecter', "Choose ONE Item", choices = c("small","big")),
  selectizeInput('chooser', 'Choose SEVERAL Items', choices = NULL, multiple = TRUE)
)

server=function(input,output,session){

  #DatafromMytable=read.csv("mytable.csv", header=TRUE, sep=";")
  DatafromMytable=data.frame(Size=c('small','small','big','big'),Item=c(1,2,3,4))

  mysubset= reactive ({
    subset(DatafromMytable,Size==input$selecter)
    })

  observeEvent( mysubset(),{
  updateSelectizeInput(session, "chooser", choices = mysubset()$Item) 
  })

}

shinyApp(ui, server)

The simplest solution seems to be to just wrap the two lines that have reactive variables with observe({ ... }) .

 observe({  
 mysubset=subset(DatafromMytable,Size==input$selecter)
 updateSelectizeInput(session, "chooser", choices = mysubset$Item) 
 })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM