Can you set a Shiny input with a custom message and return it within one function?

Hello! I have a question about the delay between Shiny/JS when sending custom messages.

As a toy example, consider two functions:

get_text <- function() {
  session <- shiny::getDefaultReactiveDomain()
  session$sendCustomMessage("get_text", list())
}

append_text <- function(id) {
  get_text()
  session <- shiny::getDefaultReactiveDomain()
  paste(session$input[[id]], session$input$testText)
}

As seen, append_text() calls get_text() within it. The custom message below sets the input value for 'testText' when triggered.

Shiny.addCustomMessageHandler('get_text', function(params) {
  let text = $('#test-text').html();              
  if (typeof(text) !== 'undefined') {message = text;} else {message = 'NA';}
  Shiny.onInputChange('testText', message);
});

So, the append_text() function should set the value of input$testText and return it when executed. Instead, it takes an extra function call of append_text() for that to occur. I'm not exactly sure what the issue is, but I'm guessing the delay between R to JS and back takes longer than append_text() does. I tried implementing a Sys.sleep() but that did not work either.

A full example with comments can be found here. Any advice on how I may achieve this (or possible alternatives) would be greatly appreciated!

This topic was automatically closed 54 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.