Get value from reactive context in R shiny based on user input

I need to change the value of mydb (string) based on the input selected from the sidebar.

ui.R

library(shiny)
shinyUI(fluidPage(
  titlePanel("Shiny App"),
  sidebarLayout(
    sidebarPanel( selectInput("site", 
                          label = "Choose a site for Analysis",
                          choices = c("abc", "def",
                                      "ghi", "jkl"),
                          selected = "abc")
              ),
    mainPanel(
      textOutput("text"),
     )
))

server.R

library(shiny)
library(ggplot2)
library(RMySQL)

shinyServer(function(input, output) {
    if(input$site=="abc"){
      mydb<-"testdb_abc"}
   else if(input$site=="def"){
     mydb<-"testdb_def"}
      con <- dbConnect(MySQL(),dbname=mydb, user="root", host="127.0.0.1", password="root")
      query <- function(...) dbGetQuery(con, ...)  

      output$text <- renderText({
        paste("You have selected:",input$site)
      })  

})

In the above server.R, I need to assign the string value mydb based on the selected input. I get 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.) 

How can I do this with reactive shine?

+4
source share
1 answer

, if observe . , , . mydb() , ( , ):

con <- dbConnect(MySQL(),dbname=mydb(), user="root", host="127.0.0.1", password="root")
query <- function(...) dbGetQuery(con, ...) 

library(shiny)
library(ggplot2)
library(RMySQL)

ui =fluidPage(
  titlePanel("Shiny App"),
    sidebarPanel(selectInput("site", 
                              label = "Choose a site for Analysis",
                              choices = c("abc", "def","ghi", "jkl"),selected = "abc")),
    mainPanel(textOutput("text"),textOutput("db_select"))
  )


server = (function(input, output) {

  mydb <- reactive({

    if(input$site == "abc")
      {
        test <- c("testdb_abc")
      }
    else if(input$site == "def")
      {
        test <- c("testdb_def")
      } 
  })

  output$text <- renderText({  
    paste("You have selected:",input$site)
  })  

  query_output <- reactive({
    con <- (dbConnect(MySQL(),dbname=mydb(), user="root", host="127.0.0.1", password="root"))
    query <- function(...) dbGetQuery(con, ...)   
  })

  output$db_select <- renderText({  
    paste("My Database is:",mydb())
  })  
})


runApp(list(ui = ui, server = server))
+7

All Articles