10 Dashboard drill-down

10.1 Add a tabset to the dashboard

Prepare the ui to accept new tabs based on the user’s input

  1. Wrap the “output” functions in the ui with a tabPanel()
# Goes from this
valueBoxOutput("total"),
dataTableOutput("monthly")

# To this
tabPanel(
  valueBoxOutput("total"),
  dataTableOutput("monthly")
  )
  1. Set the panel’s title and value. The new code should look like this
tabPanel(
  title = "Dashboard", 
  value = "page1", 
  valueBoxOutput("total"),
  dataTableOutput("monthly")
  )
  1. Wrap that code inside a tabsetPanel(), set the id to tabs
tabsetPanel(
  id = "tabs",
  tabPanel(
    title = "Dashboard",
    value = "page1",
    valueBoxOutput("total"),
    dataTableOutput("monthly")
  )
)
  1. Re-run the app

10.2 Add interactivity

Add an click-event that creates a new tab

  1. Set the selection and rownames in the current datatable() function
output$monthly <- renderDataTable(datatable({
  base_dashboard() %>%
    group_by(month) %>%
    tally() %>%
    collect() %>%
    mutate(n = as.numeric(n)) %>%
    rename(flights = n) %>%
    arrange(month)}, 
  list( target = "cell"),    # New code
  rownames = FALSE))         # New code
  1. Use observeEvent() and appendTab() to add the interactivity
observeEvent(input$monthly_cell_clicked, {
  appendTab(
    inputId = "tabs", # This is the tabsets panel's ID
    tabPanel(
      "test_new", # This will be the label of the new tab
      renderDataTable(mtcars, rownames = FALSE)
    )
  )
}) 
  1. Re-run the app

  2. Click on a row inside the datatable and then select the new tab called test_new to see the mtcars data

10.3 Add title to the new tab

Use the input’s info to create a custom label

  1. Load the clicked cell’s info into a variable, and create a new lable by concatenating the cell’s month and the selected airline’s code
observeEvent(input$monthly_cell_clicked, {
  cell <- input$monthly_cell_clicked # New code

  if (!is.null(cell$value)) { # New code
    tab_title <- paste0(month.name[cell$value], "_", input$select)
    appendTab(
      inputId = "tabs",
      tabPanel(
        tab_title, # Changed code
        renderDataTable(mtcars, rownames = FALSE)
      )
    )
  }
})
  1. Re-run the app, and click on one of the month’s to confirm that the new label works

  2. Use updateTabsetPanel to switch the dashboard’s focus to the newly created tab. It goes after the tabPanel() code

updateTabsetPanel(session, "tabs", selected = tab_title)

10.4 pool pakcage

Improve connectivity using the pool package

1.Change dbConnect() to dbPool()

# Goes from this
con <- DBI::dbConnect(odbc::odbc(), "Postgres Dev")

# To this
con <- pool::dbPool(odbc::odbc(), dsn =  "Postgres Dev")
  1. Add an onStop() step to close the pool connection
onStop(function() {
  poolClose(con)
})