ixodid
ixodid

Reputation: 2400

Basic Shiny Question - Making Program Variables Reactive?

I have a simple Shiny app that displays a question in the main panel. The questions are simply 10, 20 or 30.

The result of being "Right" or "Wrong" is displayed in the R Console.

You can then click an ActionButton, "Next" to go to the next question, which should be displayed in the mainPanel. Currently, the question is not displayed but the indexing is working.

It is unclear to me how to get the second question to display. I believe I need to make "questions" or "question_index" a reactive variable?? Not sure.

Also, I am using a global variable for question_index which I believe is bad form. Again, not sure what the alternative is.

js <- '
$(document).on("keyup", function(e) {
if(e.keyCode == 13){
Shiny.onInputChange("keyPressed", Math.random());
}
});
'

shinyApp(
  ui = fluidPage(
    tags$script(js),

    sidebarLayout(
      sidebarPanel(
        textInput("answer", 
          width = "50px",
          label = "Answer"),

      actionButton(
        inputId = "next_question",
        label = "Next"
      )
    ),

      mainPanel(
        textOutput("equation")
      )
    )
  ),

  server = function(input, output, session){

    questions <- c("10", "20", "30")
    question_index <<- 1

    Answer <- reactiveVal()

    observeEvent(input$keyPressed, {
      Answer(input$answer)
      if (input$answer == questions[question_index]) {
        print("Right")
      } else {
        print("Wrong")
      }
    })

    output$equation <- renderText({
     # Answer()
      questions[question_index]
    })

    observeEvent(input$next_question, {
      question_index <<- question_index + 1
      print(question_index)
    })

  }
)

Upvotes: 0

Views: 32

Answers (1)

MonikaP
MonikaP

Reputation: 147

One way is indeed to make question index reactive like this

values <- reactiveValues(question_index=1)

and then call it as

values$question_index

Upvotes: 1

Related Questions