Skip to content

Instantly share code, notes, and snippets.

@jdtrat
Last active April 3, 2021 21:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jdtrat/a349bf4a8a94d10ef1195c3e8cc6a61d to your computer and use it in GitHub Desktop.
Save jdtrat/a349bf4a8a94d10ef1195c3e8cc6a61d to your computer and use it in GitHub Desktop.
Minimal example illustrating a delay in communicating between JS and Shiny.
get_text <- function() {
session <- shiny::getDefaultReactiveDomain()
session$sendCustomMessage("get_text", list())
}
# append the text from a given ID with the result of "get_text" from JS
append_text <- function(id) {
get_text()
session <- shiny::getDefaultReactiveDomain()
paste(session$input[[id]], session$input$testText)
}
library(shiny)
ui <- fluidPage(
tags$script("
Shiny.addCustomMessageHandler('get_text', function(params) {
let text = $('#test-text').html();
if (typeof(text) !== 'undefined') {message = text;} else {message = 'NA';}
Shiny.onInputChange('testText', message);
});
"),
p(id = "test-text", "appending this"), # define a p tag with id "test-text" that is read by the JS function
textInput("userText", "Input Text"),
actionButton("getText", "Get Text"),
verbatimTextOutput("appended")
)
server <- function(input, output, session) {
text <- reactiveVal()
# when action button "getText" is pressed, call `append_text()`
# and set the reactive value text equal to the results
observeEvent(input$getText, {
text(append_text(id = "userText"))
})
# render the reactive value text.
# takes two clicks for the appending to work correctly.
output$appended <- renderText({
text()
})
}
shinyApp(ui, server)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment