7

Situation: I want to print an input variable from the R shiny UI to the console. Here is my code:

library(shiny)

ui=fluidPage(
  selectInput('selecter', "Choose ONE Item", choices = c("small","big"))
)

server=function(input,output,session){
  print("You have chosen:")
  print(input$selecter)
 }

shinyApp(ui, server)

Unfortunately I get this error message:

Error in .getReactiveEnvironment()$currentContext() : 
  Operation not allowed without an active reactive context. (You tried to do something that can only be done from inside a reactive expression or observer.)

Question: What do I need to change my code to, in order to make it work?

nexonvantec
  • 572
  • 1
  • 5
  • 18
  • https://shiny.rstudio.com/articles/debugging.html, look at `printf` tracing – Jake Kaupp Jan 16 '18 at 15:41
  • 4
    The problem is not the `print` statement itself, it's the reference of `input$selecter` from outside of a reactive statement. It needs to be within a `observe`, `observeEvent`, (`reactive`, I think), or similar function. – r2evans Jan 16 '18 at 15:45
  • Try `observeEvent(input$selecter, {cat("You have chosen:", input$selecter)})` in `server`. – Sagar Jan 16 '18 at 15:52

1 Answers1

12

You should use an observeEvent which will execute every time the input changes:

library("shiny")

ui <- fluidPage(
    selectInput('selecter', "Choose ONE Item", choices = c("small","big")),
    verbatimTextOutput("value")  
)

server <- function(input, output, session){

  observeEvent(input$selecter, {
    print(paste0("You have chosen: ", input$selecter))
  })

}

shinyApp(ui, server)

enter image description here

mlegge
  • 6,763
  • 3
  • 40
  • 67