I got an app that when you click on an actionButton, it should set an input to a certain value; and a click action should be made through shinyjs. However, only the first thing is happening; and I don't know how to make the second one happen. Or maybe it IS happening; but the data inside the reactive object is not getting updated.
Heres a minimal reprex:
library(shiny)
ui <- fluidPage(
shinyjs::useShinyjs(),
selectInput("selector", label = "Carb selector", choices = unique(mtcars$carb)),
actionButton("generate", "OK!"),
tableOutput("results"),
actionButton("reset", "RESET"),
)
server <- function(input, output, session) {
data <- reactive({
req(input$generate)
isolate(
mtcars %>% filter(carb == input$selector)
)
})
output$results <- renderTable(data())
observeEvent(input$reset, {
updateSelectInput(session,
inputId = "selector",
label = "Carb selector updated",
choices = unique(mtcars$carb),
selected = 1)
shinyjs::click("generate")#This does not seem trigger when you hit reset!
})
}
shinyApp(ui, server)
Why this behavior?
The architecture of your code is a bit questionable, but I will point out why it is behaving this way.
To understand this, let's first break the observer on
input$resetinto two:After that, let's have a look at the documentation of
updateSelectInput:And there lies the answer. In other words,
shinyjs::click("generate")will always execute beforeupdate*Input()effects kick in.Basically, this is the flow:
Suggested solution
We can use number 4 above to our advantage by having a
reactiveVal()that always has the most current value of 'selector' and is a step ahead ofupdate*Input().I have made a few changes to your code to make it more explicit and straight to the point.