Skip to content

Instantly share code, notes, and snippets.

@timelyportfolio
Created March 30, 2018 15:28
Show Gist options
  • Save timelyportfolio/f962420e8b0e7e7ce33a5e085bfcdffe to your computer and use it in GitHub Desktop.
Save timelyportfolio/f962420e8b0e7e7ce33a5e085bfcdffe to your computer and use it in GitHub Desktop.
shiny datatables update streaming

Let's say you have streaming data, and you would like to update a DT::datatable in Shiny without completely re-rendering the table. Here is some code to illustrate how this might be accomplished. Hope it helps.

library(DT)
library(shiny)

ui <- tagList(
  tags$script(HTML(
"
Shiny.addCustomMessageHandler(
  'updateTable',
  function(e) {
    var row = e.row,
      col = e.col,
      value = e.value

    if($('#tbl table').DataTable) {
      $('#tbl table').DataTable().cell(row - 1, col - 1).data(value)
    }
  }
)
"
  )),
  DT::DTOutput("tbl")
)

server <- function(input, output, session) {
  output$tbl <- DT::renderDT(
    {
      DT::datatable(
        data.frame(
          id = LETTERS,
          value = round(runif(26, 20, 40), 2)
        ),
        rownames = FALSE
      )
    },
    server = FALSE
  )
  
  observe({
    invalidateLater(100, session)
    session$sendCustomMessage(
      "updateTable",
      list(
        row = floor(runif(1,1,26.99)),
        col = 2,
        value = round(runif(1,20,40), 2)
      )
    )
  })
}

shinyApp(ui, server)
library(DT)
library(shiny)
ui <- tagList(
tags$script(HTML(
"
Shiny.addCustomMessageHandler(
'updateTable',
function(e) {
var row = e.row,
col = e.col,
value = e.value
if($('#tbl table').DataTable) {
$('#tbl table').DataTable().cell(row - 1, col - 1).data(value)
}
}
)
"
)),
DT::DTOutput("tbl")
)
server <- function(input, output, session) {
output$tbl <- DT::renderDT(
{
DT::datatable(
data.frame(
id = LETTERS,
value = round(runif(26, 20, 40), 2)
),
rownames = FALSE
)
},
server = FALSE
)
observe({
invalidateLater(100, session)
session$sendCustomMessage(
"updateTable",
list(
row = floor(runif(1,1,26.99)),
col = 2,
value = round(runif(1,20,40), 2)
)
)
})
}
shinyApp(ui, server)
@timelyportfolio
Copy link
Author

streaming_dt

@stewartli
Copy link

very useful. thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment