Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner Author

commented Mar 30, 2018

streaming_dt

@stewartli

This comment has been minimized.

Copy link

commented Oct 26, 2018

very useful. thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.