0

I am baffled why the following code produces the "Shiny.setInputValue is not a function" error:

library(shiny)
library(htmltools)

# Define UI for application that draws a histogram
ui <- fluidPage(
    
    
    # Application title
    titlePanel("Test"),

    # Sidebar with a slider input for number of bins 
    sidebarLayout(
        sidebarPanel(
            
        ),

        # Show a plot of the generated distribution
        mainPanel(
          shiny::tags$script(htmltools::HTML('
  quantityaa = 1;
  console.log(quantityaa);
  Shiny.setInputValue("hi", quantityaa);
                                  '))
       ,
       
        )
        )
        
)

# Define server logic required to draw a histogram
server <- function(input, output) {
    
    hi <- reactive({ input$hi})
    print(hi)
    
}

# Run the application 
shinyApp(ui = ui, server = server)

What is wrong with this code that produces this error? I cannot see anything wrong with it, but I must be missing something.

eartoolbox
  • 327
  • 2
  • 10
  • Does this answer your question? [How to use shiny javascript functions?](https://stackoverflow.com/questions/54039338/how-to-use-shiny-javascript-functions) – ismirsehregal Oct 07 '20 at 11:20

1 Answers1

4

That's because Shiny is not ready yet. Use the shiny:connected event:

$(document).on("shiny:connected", function() {
  // your awesome JavaScript here can use Shiny.setInputValue
});
Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225