Reputation: 352
I'm trying to use a selectInput in a dynamic sql query with Shiny but the reactive state seems to go awry :
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.)
I am actually using RODBC with a sql query but this is an attempt at a reproducible example.
Server :
data(citytemp, package = "highcharter")
function(input, output) {
getCityData <- function(selectedCity) {
return(citytemp[[selectedCity]])
# hardcoded :
# return(citytemp$tokyo)
# dynamic sql query
# sql <- paste0("select * from cities where name = ", selectedCity)
}
cityData <- getCityData(input$cityFilter)
#render highchart with cityData
}
UI :
library("shiny")
library("shinydashboard")
selectInput("cityFilter", label = "City", choices = list("Tokyo" = "tokyo", "London" = "london", "Berlin" = "berlin"))
box(width = 6, highchartOutput("highchart"))
Upvotes: 0
Views: 1137
Reputation: 352
Here's the working solution if anyone is looking for it.
github : dynamic query from reactive shiny widget
Upvotes: 0
Reputation: 1723
Basic example, make sure to state reactive({getCityData(input$cityFilter)})
.
library(shiny)
library(shinydashboard)
library(highcharter)
ui <- dashboardBody(
selectInput("cityFilter", label = "City", choices = list("Tokyo" = "tokyo", "London" = "london", "Berlin" = "berlin")),
box(width = 6, highchartOutput("highchart") )
)
server = function(input, output){
data(citytemp, package = "highcharter")
getCityData <- function(selectedCity) {
return(citytemp[[selectedCity]])
# hardcoded :
# return(citytemp$tokyo)
# dynamic sql query
# sql <- paste0("select * from cities where name = ", selectedCity)
}
cityData <- reactive({getCityData(input$cityFilter)})
output$highchart <- renderHighchart({
selectedCityData <- cityData()
print("selected city data is")
print(selectedCityData)
hc <- highchart(type = "chart") %>%
hc_add_series( name = input$cityFilter,
data = selectedCityData )
theme <- hc_theme_null()
hc <- hc %>% hc_add_theme(theme)
return(hc)
})
}
shinyApp(ui=ui, server=server)
Upvotes: 1
Reputation: 29387
Since you are using the client inputs they have to be either in a reactive
expression or in observer
, try this:
cityData <- reactive({getCityData(input$cityFilter)})
output$highchart <- renderHighchart({cityData()})
Upvotes: 3