Kewl
Kewl

Reputation: 3417

Execute function only on first button press in rshiny

In my shiny app, I have a render that I want to only execute after a radio button changes values, but only the first time this happens. Is there a way to make it reactive to the first change in value, but not subsequent ones?

Upvotes: 1

Views: 999

Answers (1)

Pork Chop
Pork Chop

Reputation: 29387

Below you will find that observeEvent has arguments such as ignoreInit and once, I would advise that you go and have a look at the function definitions on the official website Event handler. I have also added the shinyjs library with its disable function which I think is handy here.

rm(list=ls())
library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  radioButtons("nums", "Will Execute only Once",c("1000" = 1000,"10000" = 10000), selected = 0),
  plotOutput("Plot")
)

server <- function(input, output) {
  v <- reactiveValues()
  observeEvent(input$nums, {
    v$data <- rnorm(input$nums) 
  },ignoreInit = TRUE, once = TRUE)

  output$Plot <- renderPlot({
    if(is.null(v$data)){
      return()
    }
    disable('nums')
    hist(v$data)
    box()
  })
}

shinyApp(ui, server)

enter image description here

Upvotes: 3

Related Questions