I need to change the mydb(string) value based on input selected from sidebar.
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"),
)
))
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 above server.R, I need to assign string value to mydb based on 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 that with reactive in shiny?
as previously mentioned you would have to have your if statements in the reactive expression or observe
Below is the working example of the sample App. Here I used a reactive expression to check which database you have selected. you can then use the mydb() and put it into your query, like so (I think this should work):
con <- dbConnect(MySQL(),dbname=mydb(), user="root", host="127.0.0.1", password="root")
query <- function(...) dbGetQuery(con, ...)
A sample example is below
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With