I am trying to make a shiny app that takes a numerical value that is used to filter a dataset and returns the filtered data as a table. I can get the app to do what I want, but when I insert validate() to be able to return a custom message when the filter input is not a valid value.
This is the code that I have:
in_data <- mtcars %>%
distinct(hp, .keep_all = T)
ui <- navbarPage("demo",
collapsible = T,
tabPanel("Cars One", uiOutput("page1")),
tabPanel("Car Tool", uiOutput("page2"))
)
server <- function(input, output){
output$page1 <- renderUI({
renderText('Page One')
})
output$page2 <- renderUI({
fluidPage(
sidebarLayout(
sidebarPanel(
numericInput(
'input_hp', 'Enter HP:', 1, min = 1
)
),
mainPanel(
DTOutput('car_spec')
)
)
)
})
car_data <- reactive({
in_data %>%
filter(hp == input$input_hp) %>%
t()
})
output$car_spec <- DT::renderDT({
# check that the hp is available
validate(need(nrow(car_data()) < 1,
"Choose a different HP."))
DT::datatable(
car_data(),
options = list(
pageLength = 20,
autoWidth = F,
scrollX=T,
dom = 't'
) # end of options
)
})
}
# Run the application
shinyApp(ui = ui, server = server)
I am using a toy dataset here (mtcars), but in reality, what I want to filter doesn’t have solid boundaries (besides being a positive integer). Using the above code, everything works as expected when I enter a valid value (93, for example). However, with the validate() portion, nothing updates even when I entered a valid value. My original app is a 2 pager with something else on the first page, so that’s why I have the first page here. Not really related to the issue.