Reputation: 715
In a shiny app, I check the validity of an input with req
and update an output if the requirement on the input is TRUE (i.e. not empty, not FALSE, etc.).
I would like to run some code if the req
is FALSE, i.e. use a req() else {}
-like structure.
I could use an if() {} else {}
conditional structure, but the req
tests many things that I would prefer to avoid implementing myself.
Here is a MWE:
text_in
is valid, a reactive value local$text
is updated.text_out
.text_in
is not valid, I would like to execute some code, e.g. local$text <- "no text"
Note: I could run local$text <- "no text"
before using the req
but the app I am developing (not this example) uses multiple req
and I cannot define a "default" value before calling these req
.
library(shiny)
ui <- fluidPage(
textInput("text_in", label = "write", value = "default"),
verbatimTextOutput("text_out", placeholder = TRUE)
)
server <- function(input, output) {
local <- reactiveValues(text = NULL)
observe({
req(input$text_in)
local$text <- input$text_in
# else {
# local$text <- "no text"
# }
})
output$text_out <- renderText({
local$text
})
}
shinyApp(ui = ui, server = server)
Solution proposed by @mr-putter using shiny::isTruthy
:
observe({
if(isTruthy(input$text_in)) {
local$text <- input$text_in
} else {
local$text <- "no text"
}
})
Upvotes: 3
Views: 1113
Reputation: 5254
req
returns "the first value that was passed in". So, you should be able to do something like this:
observe({
if(isTruthy(input$text_in))
local$text <- input$text_in
else {
local$text <- "no text"
}
})
Upvotes: 3