Home > OS >  How to make actionbutton only work every time it is pressed?
How to make actionbutton only work every time it is pressed?

Time:06-11

Hello and thanks for reading me. I am currently trying to make a simple app in shiny that allows you to filter a dataframe, but I would like the filter to update every time I press the button. It works the first time, but apparently afterwards the observeEvent stays activated and the information is filtered even if you don't press the button. Is there any way to avoid this?

The code is the following:

library(shiny)
library(dplyr)
library(shinyWidgets)

x <- tibble(
  val1 = 1:5,
  val2 = sample(letters,5)
)

shinyApp(
  ui = fluidPage(
    column(width = 3, pickerInput("filt", "filter",
                                  choices = x$val1,
                                  selected = x$val1,
                                  multiple = TRUE
                                  ),
           actionButton("ready", "filter data")
           ),
    column(width = 6, textOutput("text"))
  ),
  server = function(input, output, session){
    
    
    observeEvent(input$ready,{
      
      output$text <- renderText({
        
        x <- x |> 
          filter(val1 %in% input$filt)
        
        
        print(x$val2)
        
      })
      
      
    })
    
    
    
  }
)

I think the problem is in this part:

observeEvent(input$ready,{
      
      output$text <- renderText({
        
        x <- x |> 
          filter(val1 %in% input$filt)
        
        
        print(x$val2)
        
      })
      
      
    })

Thanks a lot for the help

CodePudding user response:

Use the bindEvent function in shiny

library(shiny)
library(dplyr)
library(shinyWidgets)

x <- tibble(
  val1 = 1:5,
  val2 = sample(letters,5)
)

shinyApp(
  ui = fluidPage(
    column(width = 3, pickerInput("filt", "filter",
                                  choices = x$val1,
                                  selected = x$val1,
                                  multiple = TRUE
    ),
    actionButton("ready", "filter data")
    ),
    column(width = 6, textOutput("text"))
  ),
  server = function(input, output, session){
    
    output$text <- renderText({
      
      x <- x |> 
        filter(val1 %in% input$filt)
      
      print(x$val1)

    }) |> 
      bindEvent(input$ready)
    
    
    
    
  }
)

CodePudding user response:

Try putting it in an eventReactive() call instead of observeEvent(). Your server function would look like this instead:

  server = function(input, output, session) {

    filter_data <- eventReactive(input$ready, {

      x <- x %>%
        filter(val1 %in% input$filt)

    })

    output$text <- renderText({

      filter_data()$val2

    })

  }
  • Related