Retrasa reacciones con eventReactive()
El marco de programación reactiva de Shiny está diseñado para que cualquier cambio en las entradas actualice automáticamente las salidas que dependen de ellas. En algunas situaciones, quizá queramos controlar explícitamente el disparador que provoca la actualización.
La función eventReactive() se usa para calcular un valor reactivo que solo se actualiza en respuesta a un evento específico.
rval_x <- eventReactive(input$event, {
# calculations
})
Este ejercicio forma parte del curso
Creación de aplicaciones web con Shiny en R
Instrucciones del ejercicio
- Usa
eventReactive()para retrasar el cálculo del IMC hasta que el usuario haga clic en el botón.
Ejercicio interactivo práctico
Prueba este ejercicio y completa el código de muestra.
ui <- fluidPage(
titlePanel('BMI Calculator'),
sidebarLayout(
sidebarPanel(
textInput('name', 'Enter your name'),
numericInput('height', 'Enter height (in m)', 1.5, 1, 2, step = 0.1),
numericInput('weight', 'Enter weight (in Kg)', 60, 45, 120),
actionButton("show_bmi", "Show BMI")
),
mainPanel(
textOutput("bmi")
)
)
)
server <- function(input, output, session) {
# MODIFY CODE BELOW: Use eventReactive to delay the execution of the
# calculation until the user clicks on the show_bmi button (Show BMI)
rval_bmi <- reactive({
input$weight/(input$height^2)
})
output$bmi <- renderText({
bmi <- rval_bmi()
paste("Hi", input$name, ". Your BMI is", round(bmi, 1))
})
}
shinyApp(ui = ui, server = server)