Octave1 Octave1 - 3 months ago 17
R Question

How to overwrite output using 2nd action button

I have a shiny app which writes a dataframe to output when an action button is pressed. This is the "Go" button in the bare-bones example below. I have a reset button which resets the values of the inputs. I'm wondering how I might also reset the output (so it becomes NULL & disappears when "reset" is pressed).

I've tried to pass

input$goButtonReset
to the
eventReactive
function (with the intention of using an if statement inside to indicate which button was making the call) but this didn't seem to be possible.

Any help much appreciated!

ui <- fluidPage(title = "Working Title",

sidebarLayout(

sidebarPanel(width = 6,
# *Input() functions
selectInput("Input1", label = h3("Select Input1"),
choices = list("A" = "A", NULL = "NULL"),
selected = 1),
actionButton("goButton", "Go!"),
p("Click the button to display the table"),
actionButton("goButtonReset", "Reset"),
p("Click the button to reset your inputs.")
),

mainPanel(
# *Output() functions
tableOutput("pf"))
)

)

# build the outputs here
server <- function(input, output, session) {

observeEvent(input$goButtonReset, {
updateSelectInput(session, "Input1", selected = "NULL")
})

writePF <- eventReactive(input$goButton, {
data.frame("test output")
})

output$pf <- renderTable({
writePF()
})

}

shinyApp(ui = ui, server = server)

Answer

You could try using reactiveValues to store the data frame. This worked for me:

    ui <- fluidPage(title = "Working Title",

                sidebarLayout(

                  sidebarPanel(width = 6,
                               # *Input() functions
                               selectInput("Input1", label = h3("Select Input1"),
                                           choices = list("A" = "A", NULL = "NULL"),
                                           selected = 1),
                               actionButton("goButton", "Go!"),
                               p("Click the button to display the table"),
                               actionButton("goButtonReset", "Reset"),
                               p("Click the button to reset your inputs.")
                  ),

                  mainPanel(
                    # *Output() functions
                    tableOutput("pf"))
                )

)

# build the outputs here
server <- function(input, output, session) {

  df <- reactiveValues()  

  observeEvent(input$goButton,{    
    df$writePF <- data.frame("test output")    
  })

  observeEvent(input$goButtonReset,{    
    df$writePF <- NULL    
  })


  output$pf <- renderTable({
    df$writePF
  })  

}

shinyApp(ui = ui, server = server)