Abhishek Agnihotri
Abhishek Agnihotri

Reputation: 317

How to stop resetting a variable in R-Shiny?

I am working on an Interactive Shiny App. To display the next plot on a mouse click, I have to track the very previous value of a variable. But when I click on the plot All the variables reset. Can you please suggest me a way to stop a variable from resetting on every iteration.

For example:

library(shiny)

ui <- shinyUI(fluidPage(
  titlePanel("Title"),
  sidebarLayout(
    sidebarPanel(
      actionButton("Reset", label="Reset Graph")
    ),
    mainPanel(
      plotOutput("graph", width = "100%", click = "plot_click"),
      verbatimTextOutput("click_info")
    )
  )
) 
)

server <- shinyServer(function(input, output, session) { 
level <- "Value1"  
observeEvent(input$Reset,{   
output$graph <- renderPlot({ plot(1, 1) }) }, ignoreNULL = F)
  print(level)
  # interaction click in graph  
  observe({
    if(is.null(input$plot_click$x)) return(NULL)
    x <- sample(20:30,1,F)
    level <- "Value2"
    isolate({
      output$graph <- renderPlot({
        draw.single.venn(x)
      }) 
    })

  })

})
shinyApp(ui=ui,server=server)

I have changed the level variable to "Value2". But on next iteration, it again turns to "Value1" due to the first line of code. Can you help me to remain it as "Value2"?

Upvotes: 1

Views: 512

Answers (1)

LocoGris
LocoGris

Reputation: 4480

You can define it as a reactive value:

server <- shinyServer(function(input, output, session) { 
  level_init <- reactiveValues(level="Value1") 
  level_react <- reactive({
    level_init$level <- "Value2"
  })
  print(isolate(level_init$level))
  observeEvent(input$Reset,{   
    output$graph <- renderPlot({ plot(1, 1) }) }, ignoreNULL = F)
  # interaction click in graph  
  observe({
    if(is.null(input$plot_click$x)) return(NULL)
    x <- sample(20:30,1,F)
    level_react()
    print(level_init$level)
    isolate({
      output$graph <- renderPlot({
        draw.single.venn(x)
      }) 
    })

  })

})
shinyApp(ui=ui,server=server)

Upvotes: 1

Related Questions