'Action button increments and observeEvent runs that many times

I'm trying to update the selectInput (Unique of a column) after the file input and then wait for the action button to trigger, so that I could run the rest of my code for that selected input.

However, I have used observeEvent to track actionbutton trigger.

The code runs perfectly the first time, after which I submit the file again on the same session and it causes the observeEvent to run two times.

ui.R

ui <- fluidPage(
  fileInput("file", label = "dataset input", accept = ".csv"),
  selectInput("sel", label = "choose option", "options"),
  actionButton("go", "Run")
)

server.R

server <- function(input, output, session){
  observeEvent(input$file, {
    data = input$file
    if(is.null(data))
      return(NULL)
    
    df = read.csv(data$datapath)
    updateSelectInput(session, inputID="sel", choices = unique(df$items))
    observeEvent(input$go, {
      selectedoption <- input$sel
      print(paste0("this is selected", selected option))
      
      #basically this gets printed once at first time, and 2 times after the 
      #input is given again on the same session
      
    }
    }


Solution 1:[1]

Give this a go:

library(shiny)

ui <- fluidPage( 
  fileInput("file",label="dataset input",accept=".csv"), 
  selectInput("sel",label="choose option","options"), 
  actionButton("go","Run") 
)

server <- function(input,output,session){ 
  
  data <- eventReactive(input$fils,{
    req(input$file)
    read.csv(data$datapath)
  })
  
  observeEvent(data(),{
    updateSelectInput(session, inputID="sel",choices=unique(data()$items))
  })
  
  observeEvent(input$go,{
    req(input$sel)
    print(paste0("this is selected ",input$sel))
  }) 
  
}

shinyApp(ui = ui, server = server)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Pork Chop