Search code examples
rshiny-servershiny

R Shiny accessing a dynamic input


I am new to shiny, I have been stuck on this for quite a while and the things I tried and read so far held no fruits. I have a dropdown, where the user will choose a Question, then depending on the question, a drop down will be populated with the response numbers. After the user chooses the response number a map will be plotted. I have gone through the dynamic drop down list, that is done. But I cannot get access to the second user input, the response number, so I can select my data for the map accordingly. I feel like this is really simple I don't know why this does not work. I am getting this error:

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.)

My code is as follows, I have tentatively put in special cases and later I will expand to a general case with lists.

library(shiny)



runApp(list(
  ui = shinyUI(pageWithSidebar(
    headerPanel('Dialect Comparison'),
    sidebarPanel(
      selectInput('Question', 'Choose The Question', c('100. Do you cut or mow the lawn or grass?'='Q100',
                                                       '101. Do you pass in homework or hand in homework?'='Q101')),
      uiOutput('C')


    ),
    mainPanel(
      plotOutput('plot')
    )
  )
  ),


  server = function(input, output){
    output$C = renderUI({ 
      ques = input$Question
      selectInput('Choice', 'Choose The Response', seq(0,max(ling_data[,ques])))
    })



    ##########
    #The Data#
    ##########

    #text = renderPrint({'uhu'})
    #print(text()) #THIS WORKS

    choice_number = renderPrint({input$Choice}) #http://shiny.rstudio.com/gallery/dynamic-ui.html
    print(choice_number()) #it fails here

    ...
    })    

  }
))

Solution

  • Reactive variables, including inputs, can be accessed only in a reactive scope created using one of the following:

    • shiny::reactive, shiny::eventReactive
    • shiny::observe, shiny::observeEvent
    • shiny::render*

    or inside shiny::isolate block.

    For actions like logging you probably want observe block:

    observe({print(choice_number())})