logical test in observeEvent()

Hello- I have a shiny app where i want to conditionally display a modalDialog() depending on a logical test, to be tested within a call to observeEvent().

Unfortunately, observeEvent() doesn't seem to test the truth of the my logical (ie, "input$test2 != the_user" in the code below), and I seem to be missing something crucial about how to observe a shiny event.

here is a reprex; note the modal dialog is deployed ANY time the the checkbox changes and not the desired when the logical statement is true:

library(shiny)

the_user <- FALSE

ui <- fluidPage(
    checkboxInput("test2", label = "test2"),
    verbatimTextOutput("test2"),
    verbatimTextOutput("user_opt")
)

server <- function(input, output, session) {
    
    output$user_opt <- renderPrint({the_user})
    output$test2 <- renderPrint(paste("the checkbox: ", input$test2))
    
    observeEvent(input$test2 != the_user, {
        showModal(modalDialog(
            title = "my message",
            "This should only appear when the checkbox is TRUE, given that the_user is FALSE"
        ))
    })
}

shinyApp(ui, server)

any help is very appreciated

Hi,

You were pretty close to the solution :slight_smile:
The problem is that normally the observeEvent looks at the input, and will trigger the code inside as soon as the input changes (true or false) and the code inside then reacts to the value.

This is a way to solve that easily:

observeEvent(input$test2 , {
    if(input$test2 == the_user){
      showModal(modalDialog(
        title = "my message",
        "This should only appear when the checkbox is TRUE, given that the_user is FALSE"
      ))
    }    
})

Note that every click of the checkbox will run the code, but the modal only will be displayed if the conditions are right

There is another option

observeEvent(req(input$test2 == the_user), {
      showModal(modalDialog(
        title = "my message",
        "This should only appear when the checkbox is TRUE, given that the_user is FALSE"
      ))   
})

Here you use the req() function that will only produce a trigger if the conditions inside req() are met. This means that the code inside the observeEvent will only trigger if the requirements are met. Note that any event that needs to happen if the conditions are not met can't be run with this approach.

Hope this helps,
PJ

2 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.