bird
bird

Reputation: 3294

How to build a shiny app that shows the output ONLY when the user clicks a click button?

I want to build a simple shiny app, that takes a number input$number and prints this number only when the user clicks (input$click).

So far, I have tried this:

library(shiny)

ui = fluidPage(
        sliderInput("number", "number", value = 10, min = 0, max = 50),
        actionButton("click", "Change output"),
        textOutput("text")
)

server = function(input, output, session) {
        
        observeEvent(input$click, {
                output$text = renderText({
                        print(input$number)
                })
        })
}

shinyApp(ui, server)

When the app launches for the first time, it waits for the user to click before it shows the output text. However, after clicking for the first time, the app does not care if you click or not, it will automatically show the chosen number with slider.

What am I missing?

Upvotes: 0

Views: 1580

Answers (2)

Benjamin
Benjamin

Reputation: 17359

An alternative that I find helpful is to store values in a reactiveValues list and then update them using event observers.

library(shiny)

SLIDER_INIT <- 10

ui = fluidPage(
  sliderInput("number", "number", value = SLIDER_INIT, min = 0, max = 50),
  actionButton("click", "Change output"),
  textOutput("text")
)

server = function(input, output, session) {
  
  # Store values that will need to be displayed to the user here.
  AppValues <- reactiveValues(
    slider_number = 10
  )
  
  # Change reactive values only when an event occurs.
  observeEvent(
    input$click, 
    {
      AppValues$slider_number <- input$number
    }
  )
  
  # Display the current value for the user.
  output$text = renderText({
    AppValues$slider_number
  })
}

shinyApp(ui, server)

Upvotes: 1

gdevaux
gdevaux

Reputation: 2505

You can use isolate to prevent reactivity

library(shiny)

ui = fluidPage(
  sliderInput("number", "number", value = 10, min = 0, max = 50),
  actionButton("click", "Change output"),
  textOutput("text")
)

server = function(input, output, session) {

  output$text = renderText({
      input$click
      req(input$click) #to prevent print at first lauch
      isolate(print(input$number))
  })
}

shinyApp(ui, server)

Upvotes: 2

Related Questions