简体   繁体   中英

Use R Shiny selectInput in dynamic query

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

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()})

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)

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

github : dynamic query from reactive shiny widget

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM