Tim Ikata
Tim Ikata

Reputation: 221

Run SQL when selecting tab with shiny

In this shiny app, three SQLs are running at startup. However, this puts a heavy load on startup. Is it possible to run SQL when each tab is selected?

ui.R

shinyUI(
  navbarPage(title = NULL,
             tabPanel("home","hello"),
             tabPanel("1",
                      tableOutput("table1")),
             tabPanel("2",
                      tableOutput("table2")),
             tabPanel("3",
                      tableOutput("table3")))
)

server.R

shinyServer(function(input, output) {
  
  output$table1 <- renderTable({
    sql <- "SELECT * FROM City WHERE ID = '1';"
    query <- sqlInterpolate(pool, sql)
    dbGetQuery(pool, query)
  })
  
  output$table2 <- renderTable({
    sql <- "SELECT * FROM City WHERE ID = '2';"
    query <- sqlInterpolate(pool, sql)
    dbGetQuery(pool, query)
  })
  
  output$table3 <- renderTable({
    sql <- "SELECT * FROM City WHERE ID = '3';"
    query <- sqlInterpolate(pool, sql)
    dbGetQuery(pool, query)
  })
  
})

global.R

library(shiny)
library(DBI)
library(pool)

pool <- dbPool(
  drv = RMySQL::MySQL(),
  dbname = "shinydemo",
  host = "shiny-demo.csa7qlmguqrf.us-east-1.rds.amazonaws.com",
  username = "guest",
  password = "guest"
)

Upvotes: 2

Views: 141

Answers (1)

Alexis
Alexis

Reputation: 2294

You can try reactive as the code bellow:

shinyServer = function(input, output){
    reactive({
      if (req(input$navbar) == "table1")
        # Run your sql1
      if (req(input$navbar) == "table2")
        # Run your sql2
      if (req(input$navbar) == "table3")
        # Run your sql3
    })

Hope it helps.

Upvotes: 2

Related Questions