Reputation: 1479
In Shiny, the observe statements run on app load and I'd like to prevent this in some instances. For example, I might have two titles that I want to start at a certain value and after app load I want them to sync up.
In the code below if you run it, the titles will update in an infinite loop because the app immediately updates one title, then updates the other and so on. If you uncomment one of the "first_time" code blocks below then both titles will appear to start with the same value. If you uncomment both blocks then it will do what I want -- start with a pre-specified value and then sync up when changes are made.
But this code is convoluted and I don't want to add an if
statement in all observers. There must be a simpler way. In looking at the docs it seemed that perhaps using suspended = TRUE
and resume()
but I can't find examples.
I asked a related question and the answer for that one was similarly inelegant. Any thoughts?
library(shiny)
first_time1 <<- TRUE
first_time2 <<- TRUE
server <- function(input, output, session) {
observeEvent(input$title1, {
# if(first_time1){
# first_time1 <<- FALSE
# return()
# }
updateTextInput(session, "title2", value = input$title1)
})
observeEvent(input$title2, {
# if(first_time2){
# first_time2 <<- FALSE
# return()
# }
updateTextInput(session, "title1", value = input$title2)
})
}
ui <- fluidPage(
tabsetPanel(
tabPanel("A", textInput("title1", "titleA", "This is the title A")),
tabPanel("B", textInput("title2", "titleB", "This is title B"))
)
)
shinyApp(ui = ui, server = server)
Upvotes: 5
Views: 2339
Reputation: 7826
The thing you were looking for is ignoreInit
. See below
observeEvent(input$title1, {
updateTextInput(session, "title2", value = input$title1)
}, ignoreInit = T)
observeEvent(input$title2, {
updateTextInput(session, "title1", value = input$title2)
}, ignoreInit = T)
Upvotes: 5