Skip to content

Instantly share code, notes, and snippets.

@statnmap
Created September 22, 2022 15:53
Show Gist options
  • Save statnmap/9ee44ff3d371ac0e8a3d52eabb19ed14 to your computer and use it in GitHub Desktop.
Save statnmap/9ee44ff3d371ac0e8a3d52eabb19ed14 to your computer and use it in GitHub Desktop.
Why you do not want to use `render*()` inside `observeEvent()`: it does not do what you think it does
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
local <- reactiveValues(val = 0)
observeEvent(input$bins, {
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
showNotification(paste("Message", local$val), duration = 2)
isolate({local$val <- local$val + 1})
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
})
}
shinyApp(ui = ui, server = server)
@statnmap
Copy link
Author

Here, observeEvent() does not prevent renderPlot() to be updated each time loacl$val has changed, although you wanted to only trigger the code when input$bins has changed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment