youraz
youraz

Reputation: 483

Why is my else if statement not working in observeEvent?

The code is as below as an example:

library(shiny)
library(shinydashboard)

df <- data.frame(
    "obs" = 1:26,
    "letters" = LETTERS
)

ui <- dashboardPage(
    dashboardHeader(),
    dashboardSidebar(),
    dashboardBody(
        fluidRow(
            box(
                textInput("txt", "", value = ""),
                actionButton("btn1", "btn1"),
                actionButton("btn2", "btn2")
            ),
            box(
                dataTableOutput("tbl")
            )
        )
    )
)

server <- function(input, output, session) {
    
    rndDF <-
        reactiveVal(data.frame())
    
    observeEvent(input$btn1 | input$btn2, {
        updateTextInput(session, "txt", value = sample(df$letters, 1))
        if(input$btn1){
            dt <- df %>%
                filter(letters == input$txt) %>% 
                mutate(status = "ok")
            rndDF(rbind(rndDF(), dt))
        } else if (input$btn2){
            dt <- df %>%
                filter(letters == input$txt) %>% 
                mutate(status = "---")
            rndDF(rbind(rndDF(), dt))
        }
    })
    
    output$tbl <- renderDataTable({
        rndDF()
    })
    
}

shinyApp(ui, server)

The above code saves the information given by the user as a table. 'status' column will change according to user click on first or second button. The first one is working but second one is not. It also writes 'ok' to the table for the second button. What exactly am I missing? Thanks.

Upvotes: 1

Views: 896

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 389175

The reason why it behaves like this is already explained by @Alexandre Léonard . When the button is clicked you don't get TRUE/FALSE values but a number. Now to differentiate the two clicks you can have two observeEvent.

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(),
  dashboardBody(
    fluidRow(
      box(
        textInput("txt", "", value = ""),
        actionButton("btn1", "btn1"),
        actionButton("btn2", "btn2")
      ),
      box(
        dataTableOutput("tbl")
      )
    )
  )
)

server <- function(input, output, session) {
  
  rndDF <-
    reactiveVal(data.frame())
  
  observeEvent(input$btn1, {
    updateTextInput(session, "txt", value = sample(df$letters, 1))
    dt <- df %>%
      filter(letters == input$txt) %>% 
      mutate(status = "ok")
    rndDF(rbind(rndDF(), dt))
  })
  
  observeEvent(input$btn2, {
    updateTextInput(session, "txt", value = sample(df$letters, 1))
    dt <- df %>%
      filter(letters == input$txt) %>% 
      mutate(status = "ok")
    rndDF(rbind(rndDF(), dt))
  })
  
  output$tbl <- renderDataTable({
    rndDF()
  })
  
}

shinyApp(ui, server)

Upvotes: 1

Related Questions