简体   繁体   中英

R Shiny update reactive value using a non reactive variable

I have a simple text and a simple button

a variable is initialised to 0, each time the button is pressed the value of this variable is increased by 1, the dynamic text should be the concatenation of some text and the reactive value.

This is what I came up with, I am very new to reactive values so something might be wrong but I can't figure out what specifically.

the variable start, is properly initialised to 0 and the text properly rendered as clicks 0.

once I press the button the variable start is properly updated to 1, and the text accordingly. but at every other press, the variable returns to its original value 0, so the text will always be the same from the second press of the button on, equal to clicks 1.

what is updating the start variable to 0? to my understanding the server blocks is executed once, and the single input/output between frontend and backend executed when actions are triggered, but the imputation of start to zero should in theory occur only once at the startup. am I wrong?

library(shiny)

ui <- fluidPage(
  uiOutput("text_header"),
  actionButton("go", "Go") 
)

server <- function(input, output) {
  start <- 0
  rv <- reactiveVal(paste("clicks",start))
  observeEvent(input$go, {
    start <- start + 1
    rv(paste("clicks",start))
  })
  output$text_header <- renderUI({
    h1(rv(), align = "center")
  })
}

shinyApp(ui, server)

The start value needs to be reactive as well to working with other reactive values. Here's a re-write that will work

library(shiny)

ui <- fluidPage(
  uiOutput("text_header"),
  actionButton("go", "Go") 
)

server <- function(input, output) {
  start <- reactiveVal(0)
  rv <- reactive(paste("clicks",start()))
  observeEvent(input$go, {
    start(start() + 1)
  })
  output$text_header <- renderUI({
    h1(rv(), align = "center")
  })
}

shinyApp(ui, server)

We make start the reactive value, and then rv just depends completely on the current value of start . Maybe "start" isn't the best word here, you could rename it

library(shiny)

ui <- fluidPage(
  uiOutput("text_header"),
  actionButton("go", "Go") 
)

server <- function(input, output) {
  start <- 0
  clickCount <- reactiveVal(start)
  rv <- reactive(paste("clicks",clickCount()))
  observeEvent(input$go, {
    clickCount(clickCount() + 1)
  })
  output$text_header <- renderUI({
    h1(rv(), align = "center")
  })
}

shinyApp(ui, server)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM