Search code examples
rshinydatatable

Shiny Output element is rendering twice at the begining


I am building my little shiny app and I'm getting crazy for something really easy for sure.. this is a MWE:

ui.R

library(DT)

    ui <- fluidPage(
                            
      wellPanel(fluidRow(column(9,wellPanel(DTOutput('tblIris')))))
      ,wellPanel(fluidRow(column(9,textOutput('selectedRow'))))
                          
    )

server.R

options(digits.secs = 6)
printLog<-function(log){
  cat(file=stderr(),paste0("LOG ",Sys.time()," ",log,"\n"))
}
i<<-0

server <- function(input, output, session) {

  output[["tblIris"]] = renderDT({
    
    printLog("rendering tblIris")
    DT::datatable(head(iris), selection = list(target = "row",mode = 'single')
                  
    )
  })     
  
  output[["selectedRow"]] = renderPrint({
    i<<-i+1
    printLog(paste0("rendering selectedRow i=",i))
    print(paste0("row selected = ",input$tblIris_rows_selected))
    
  }
  )

  
}

It seems that the rendering of the "selectedRow" element is done twice when the application starts (only at the begining), as it is shown in the console:

LOG 2022-10-19 00:34:06.055917 rendering tblIris
LOG 2022-10-19 00:34:06.202178 rendering selectedRow i=1
LOG 2022-10-19 00:34:06.575078 rendering selectedRow i=2

Why does it happen? Is there any way to avoid this?

Thanks!!


Solution

  • You need to make sure there is a row selection by req:

        output[["selectedRow"]] = renderPrint({
            req(!is.null(input$tblIris_rows_selected))
            i<<-i+1
            printLog(paste0("rendering selectedRow i=",i))
            print(paste0("row selected = ",input$tblIris_rows_selected))
            
        }
        )