rshinyshinycssloaders

Shiny css loader is displayed even if it is not triggered yet


I have the shiny app below which creates a plot inside a box based on the user choice after clicking on the actionButton(). The iss is that I do not want the shiny css loader to be displayed before clicking the "submit".

# Load required libraries
library(shiny)
library(shinydashboard)
library(plotly)

# Define UI
ui <- dashboardPage(
  dashboardHeader(title = "SelectInput with Action Button Dashboard"),
  dashboardSidebar(),
  dashboardBody(
    # Box with selectInput and actionButton
    box(
      title = "SelectInput and ActionButton Box",
      width = 6,
      height = 400,
      solidHeader = TRUE,
      collapsible = TRUE,
      status = "primary",
      selectInput("choice", "Select a choice:", choices = c("Option 1", "Option 2")),
      actionButton("submitButton", "Submit"),
      shinycssloaders::withSpinner(
        plotlyOutput("outputPlot"),  # Output to display the plot
        type = 5,
        color = "#0dc5c1",
        size = 2)
      
    )
  )
)

# Define server
server <- function(input, output) {
  observeEvent(input$submitButton, {
    # Plot based on the selected choice
    if (input$choice == "Option 1") {
      output$outputPlot <- renderPlotly({
        # Create a plot for Option 1
        plot_ly(x = c(1, 2, 3), y = c(10, 11, 12), type = 'scatter', mode = 'lines+markers')
      })
    } else if (input$choice == "Option 2") {
      output$outputPlot <- renderPlotly({
        # Create a different plot for Option 2
        plot_ly(x = c(1, 2, 3), y = c(5, 8, 10), type = 'bar')
      })
    }
  })
}

# Create Shiny app
shinyApp(ui, server)

Solution

  • Try this

    server <- function(input, output) {
      myPlot <- eventReactive(input$submitButton, {
        myplot <- NULL
        # Plot based on the selected choice
        if (input$choice == "Option 1") {
          # output$outputPlot <- renderPlotly({
            # Create a plot for Option 1
            myplot <- plot_ly(x = c(1, 2, 3), y = c(10, 11, 12), type = 'scatter', mode = 'lines+markers')
          #})
        } else if (input$choice == "Option 2") {
          # output$outputPlot <- renderPlotly({
            # Create a different plot for Option 2
            myplot <- plot_ly(x = c(1, 2, 3), y = c(5, 8, 10), type = 'bar')
          # })
        }
        myplot
      })
      output$outputPlot <- renderPlotly({
        req(myPlot())
        myPlot()
      })
    }