Skip to content

Unintentional triggering caused by init() #23

@simon-smart88

Description

@simon-smart88

I've found this really helpful, but the way I use it, I find that init() unintentionally triggers watch() events requiring me to add req() inside render*() functions to prevent them running. Fiddling around, it seems that could be prevented by wrapping the contents of watch() in req() so it only triggers once the reactive value is > 0:

req(session$userData[[name]]() > 0)

From my testing, this seems to give the same behaviour for the examples, but also works when the returned object from the render*() is not an object in new.env.

Hopefully the example below demonstrates what I mean. out2 is rendered immediately when it shouldn't be. plot1 uses one of the values in b but still tries to render immediately, as does plot2 . out3 and plot3 using new_watch function as expected, only rendering after the trigger.

library(gargoyle)
library(shiny)

ui <- function(){
  fluidPage(
  actionButton("go", "go"),
  verbatimTextOutput("out1"),
  verbatimTextOutput("out2"),
  verbatimTextOutput("out3"),
  plotOutput("plot1"),
  plotOutput("plot2"),
  plotOutput("plot3")
  )
}

server <- function(input, output, session){

  new_watch <- function(name, session = getDefaultReactiveDomain()){
    req(session$userData[[name]]() > 0)
  }

  init("a")

  b <- new.env()

  observeEvent(input$go, {
    b$b <- "testing1"
    b$p <- rnorm(100)
    trigger("a")
  })

  output$out1 <- renderText({
    watch("a")
    b$b
  })

  output$out2 <- renderText({
    watch("a")
    "testing2"
  })

  output$out3 <- renderText({
    new_watch("a")
    "testing3"
  })

  output$plot1 <- renderPlot({
    watch("a")
    hist(b$p, main = "1")
  })

  output$plot2 <- renderPlot({
    watch("a")
    hist(rnorm(100), main = "2")
  })
  
  output$plot3 <- renderPlot({
    new_watch("a")
    hist(rnorm(100), main = "3")
  })

}

shinyApp(ui, server)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions