hadley / mastering-shiny

Mastering Shiny: a book

Home Page:https://mastering-shiny.org/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Bug at example from subsection 10.3.1

thereallda opened this issue · comments

Hi,

In Chapter 10, subsection 10.3.1 "Getting started", the app that dynamically creates input control, would throw an error when combines with isolate().

Here is the code used to create the app:

library(shiny)

ui <- fluidPage(
    textInput("label", "label"),
    selectInput("type", "type", c("slider", "numeric")),
    uiOutput("numeric")
    
)

server <- function(input, output, session) {
    output$numeric <- renderUI({
        value <- isolate(input$dynamic)
        if (input$type == "slider") {
            sliderInput("dynamic", input$label, value = value, min = 0, max = 10)
        } else {
            numericInput("dynamic", input$label, value = value, min = 0, max = 10)
        }
    })

}

shinyApp(ui = ui, server = server)

It throws error at initialization.
image

At app initialization, input$dynamic is NULL which rise the error. It could be fixed with value=0 (like default) when input$dynamic is NULL:

library(purrr)

server <- function(input, output, session) {
    output$numeric <- renderUI({
        value <- isolate(input$dynamic)
        if (input$type == "slider") {
            sliderInput("dynamic", input$label, value = value %||% 0, min = 0, max = 10)
        } else {
            numericInput("dynamic", input$label, value = value %||% 0, min = 0, max = 10)
        }
    })

}