rshinyshiny-reactivity

Numeric Input button not working with action button


I am trying to create a shiny application where I ask the user for the input of the total marketing budget. With this input, the server code will perform several operations that depend on this initial value.

However, I am facing two issues:

The Action button does not work. When I run the code, it automatically sets the initial value of the input to the "value" parameter (3243452) that I put in the numericInput. The submit button ends up being just decorative. The code example is as follows:

ui <- fluidPage(
  titlePanel("Calculadora"),
  sidebarLayout(
    sidebarPanel(
      numericInput("total_budget", "Valor total do Investimento:", value = 3243452, min = 0),
      actionButton("submit", "Otimizar")
    ),
    mainPanel(
      plotlyOutput("grafico_investimento_atual"),
      tableOutput("table")
    )
  )
 )

2.I would like my program to run every time the user changes the investment value. However, since the actionButton does not work, any change in the input value already causes the code to run again (actually, it doesn't even wait the user to give complete de value, it runs with any simply change). How can I fix this?

Observation: the input value is only used as a constant to perform a query inside the server function. The goal here is to understand how can i make a better usage of the action button (which is useless in the way that i built the UI)


Solution

  • On the server side your code needs to react to the action button. Here is a simple example of how to implement this:

    library(shiny)
    
    ui <- fluidPage(
      ui <- fluidPage(
        titlePanel("Calculadora"),
        sidebarLayout(
          sidebarPanel(
            numericInput("total_budget", "Valor total do Investimento:", value = 3243452, min = 0),
            actionButton("submit", "Otimizar")
          ),
          mainPanel(
            textOutput("test")
          )
        )
      )
    )
    
    server <- function(input, output, session) {
      
      output$test <- renderText(paste("User has selected a value of", input$total_budget)) |>
        bindEvent(input$submit)
      
    }
    
    shinyApp(ui, server)
    

    You can see that text does not render to the main panel until the action button is selected.