Question
How do I delete/invalidate the corresponding input element, when deleting a control by removeUI?
You can see in the reprex below that even after the textInput is deleted, input$x is still 'truthy'. Ideally, I could tell shiny that input$x is not valid anymore and any reactives relying on input$x treat it as if empty.
Update
Reading the answers so far, I think I was not clear, what I want to achieve. I really want to know whether one can conceptually 'nullify' input$x. In this case I would not have to take any care that something would break down the line.
Reprex
library(shiny)
ui <- fluidPage(
div(textInput("x", "Text"), id = "killme"),
actionButton("del", "Delete"),
verbatimTextOutput("out")
)
server <- function(input, output) {
output$out <- renderPrint(req(input$x))
observeEvent(input$del, removeUI("#killme"))
}
shinyApp(ui, server)
You could use reactiveValues for the printed output and assign it to NULL when deleting the div. I dont know if there is a more elegant solution.
library(shiny)
ui <- fluidPage(
div(textInput("x", "Text"), id = "killme"),
actionButton("del", "Delete"),
verbatimTextOutput("out")
)
server <- function(input, output) {
textX <- reactiveValues(x = NULL)
observe({
textX$x = input$x
})
observeEvent(input$del, {
textX$x = NULL
removeUI("#killme")
})
output$out <- renderPrint({
req(textX$x)
textX$x
})
}
shinyApp(ui, server)
This SO question, shows how to nullify an input. With this the solution becomes:
ui <- fluidPage(
tags$script("
Shiny.addCustomMessageHandler('resetValue', function(variableName) {
Shiny.onInputChange(variableName, null);
});
"),
div(textInput("x", "Text"), id = "killme"),
actionButton("del", "Delete"),
verbatimTextOutput("out")
)
server <- function(input, output, session) {
output$out <- renderPrint(req(input$x))
observeEvent(input$del, {
removeUI("#killme")
session$sendCustomMessage("resetValue", "x")})
}
shinyApp(ui, server)
Thanks for the answers though, becuase only thanks to the discussion I could make my question clearer and was able to find the right solution.
Short form using library(shinyjs):
library(shiny)
library(shinyjs)
ui <- fluidPage(
useShinyjs(debug = TRUE),
div(textInput("x", "Text"), id = "killme"),
actionButton("del", "Delete"),
verbatimTextOutput("out")
)
server <- function(input, output, session) {
output$out <- renderPrint(req(input$x))
observeEvent(input$del, {
removeUI("#killme")
runjs('Shiny.onInputChange("x", null)')
})
}
shinyApp(ui, server)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With