-
-
Save jdtrat/a349bf4a8a94d10ef1195c3e8cc6a61d to your computer and use it in GitHub Desktop.
Minimal example illustrating a delay in communicating between JS and Shiny.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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