When one actionButton is pressed, the other actionButton no longer works?

How can I modify my minimal, reproducible example Shiny app such that either dataset is loaded when you click it?

Currently if you click the first button, it works but also means you can no longer click the second button. (And vice versa). If you load the first dataset and want to then load the second one instead, you have to refresh the app.

I've tried several iterations of observe, observeEvent, and eventReactive but I couldn't get anything to work. I do need these to be inside a reactive.

Any ideas?

library(shiny)

ui <- 
  fluidPage(
  titlePanel("Output depends on which button you click first..."),
  sidebarLayout(
  sidebarPanel(),
  mainPanel(
          
         #Load mtcars 
          actionButton(inputId = "load_mtcars_normal",
                       label="load mtcars normal"
                       ),
          
          #Or Load mtcars*-999
          actionButton(inputId = "load_mtcars_alt",
                       label = "load  mtcars alt"),
          
          #Display output
          dataTableOutput("mytable")
)))

server <- function(input, output) {
  
  myreactive <- reactive({
    if(input$load_mtcars_normal){
      mydf <- mtcars
    } else if(input$load_mtcars_alt){
      mydf <- mtcars*-999
    } else {
      mydf <- NULL
    }
    
    req(mydf)
    return(list(mydf=mydf))
    
  })
  
  output$mytable <- renderDataTable(
    myreactive()$mydf
  )
  
}

shinyApp(ui = ui, server = server)

I believe the server code below produces the desired outcome. After establishing an initial NULL reactiveValue (mydf), button clicks are observed in two separate observeEvent() statements, each one updating mydf to the appropriate dataset (ignoring the NULL instance).

server <- function(input, output) {
  
  mydf = reactiveValues(d = NULL)
  
  observeEvent(input$load_mtcars_normal, { 
    mydf$d <<- mtcars
    }, ignoreNULL = T)
  
  observeEvent(input$load_mtcars_alt, { 
    mydf$d <<- mtcars * -999
    }, ignoreNULL = T)
  
  output$mytable <- renderDataTable({
    mydf$d
  })
  
}
1 Like

Thanks Scotty, you are killing it with answering Shiny questions here!

I wouldn't have thought to use two observeEvent statements with reactiveValues. Thanks, this worked!

1 Like

This topic was automatically closed 7 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.