looping error in alert generation with shinyalert

137 Views Asked by At

Good days, I am programming in Rstudio, using shiny, and I wanted to generate an alert that is activated only when I want to leave a tabPanel without completing a condition, but not if I do not enter the tabPanel before, this is the way I found. The problem is that every time that I leave the Panel 1 without fulfilling the condition of completing text, alerts are generated that are accumulating (1 alert the first time, two the second, three the third, etc.) I wanted to consult if somebody knows why it is this and how to avoid it.

thank you very much

library(shiny)
library(ggplot2)
library(shinyalert)

ui <- fluidPage(
                tabsetPanel(
                  id = "tabselected",
                  tabPanel("Tab2",""),
                  tabPanel("Tab1", textInput("requiredText", "Required Text"))
                ))

server <- function(input, output, session) {
   observe({
  req(input$tabselected == "Tab1") 
  observeEvent(
    input$tabselected, 
    if (input$tabselected != "Tab1" & !isTruthy(input$requiredText)) {
      shinyalert(title = "Save your work before changing tab",
                 type = "warning",
                 showConfirmButton = TRUE
                 )
      updateTabsetPanel(session, inputId = "tabselected", selected = "Tab1")
    }
  )
      }
    )
}

shinyApp(ui = ui, server = server)
1

There are 1 best solutions below

1
Pork Chop On

Is this the behavior you desire? Your example was recursive so you had reoccurring popup event. We can create a reactiveValues variable to keep track of the events, like so:

library(shiny)
library(ggplot2)
library(shinyalert)

ui <- fluidPage(
  tabsetPanel(
    id = "tabselected",
    tabPanel("Tab2",""),
    tabPanel("Tab1", textInput("requiredText", "Required Text"))
  ))

server <- function(input, output, session) {
  
  v <- reactiveValues(to_alert = FALSE)
  
  observeEvent(input$tabselected,{
    if (input$tabselected != "Tab1" & !isTruthy(input$requiredText)) {
      v$to_alert <- TRUE
    }else{
      v$to_alert <- FALSE
    }
  },ignoreInit = TRUE)
  
  observeEvent(v$to_alert,{
    if (v$to_alert){
      shinyalert(title = "Save your work before changing tab", type = "warning",showConfirmButton = TRUE)
      updateTabsetPanel(session, inputId = "tabselected", selected = "Tab1")
    }
  })
  
}

shinyApp(ui = ui, server = server)

enter image description here