Getting next iteration value instead of currently in shiny

Viewed 29

I have a shiynapp that updates a plot using the reactiveTimer, so it creates an animation effect. But, I'm having a problem: The iterator is getting the next iteration value. Bellow there's a simpler version of my code, that has the same issue.

library(shiny)

ui <- fluidPage(
  actionButton('play','Play'),
  textOutput('text')
)

server <- function(input, output, session) {
  timer <- reactiveTimer(1000)
  i <- 999 
  
  observeEvent(input$play,{
    i <<- 1
  })
  
  observe({
    timer()
    if(i <= 5){
      output$text <- renderText(paste0(i,'/5'))
      print(paste0(i,'/5'))
      i <<- i+1
    }
  })
}

shinyApp(ui, server)

I expected it to render like that:

1/5
2/5
3/5
4/5
5/5

That's what I'm getting in the console with the print function. But in the UI it is:

2/5
3/5
4/5
5/5
6/5

One solution would be to print render i-1, but it doesn't sound good at all. I couldn't found a more robust solution that solves this problem, can someone help me?

1 Answers

I moved paste0(i, "/5") outside of renderText() and it fixes your problem. As for why this works, but not renderText(paste0()), I cannot explain.

library(shiny)

ui <- fluidPage(
    actionButton('play','Play'),
    textOutput('text')
)

server <- function(input, output, session) {
    timer <- reactiveTimer(1000)
    i <- 999 
    
    observeEvent(input$play,{
        i <<- 1
    })
    
    observe({
        timer()
        if(i <= 5){
            counterText <- paste0(i,'/5')
            output$text <- renderText(counterText)
            print(paste0(i,'/5'))
            i <<- i+1
        }
    })
}

shinyApp(ui=ui,server=server)
Related