0

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

3 Answers 3

3

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()})
Sign up to request clarification or add additional context in comments.

Comments

1

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)

1 Comment

Thanks nilsole, that selectedCityData reference was the clincher ;-)
0

Here's the working solution if anyone is looking for it.

github : dynamic query from reactive shiny widget

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.