Cannot update the second dateRangeInput if I manually change the first dateRangeInput in R Shiny

Viewed 71

I have an example code below showing two dateRangeInput. The selected dates of the second dateRangeInput is dependent on the first dateRangeInput. Here is the same version on the Shinyapps.io (https://yuchenw.shinyapps.io/shiny_daterange/).

The strange behavior I would like to demonstrate is if I manually changed the date values in the first dateRangeInput, the second dateRangeInput becomes NA.

For example, if I selected the date in the first dateRangeInput, the app can update the second dateRangeInput successfully.

enter image description here

enter image description here

However, if I manually remove the date values in the input box of the first dateRangeInput, and then type in the new date value, the date values in the second dateRangeInput becomes NA.

enter image description here

enter image description here

It seems like a non-desired behavior as I expect these two selection methods (using calendar or manually change it) should be the same. Please let me know if I can fix this behavior.

library(shiny)

# Create the ui
ui <- fluidPage(
  dateRangeInput(inputId = "date_input1", label = "Select Date Range 1",
                 start = "2000-01-01", end = "2019-12-31",
                 min = "2000-01-01", max = "2019-12-31"),
  verbatimTextOutput(outputId = "date_output1"),
  dateRangeInput(inputId = "date_input2", label = "Select Date Range 1",
                 start = "2000-01-01", end = "2019-12-31",
                 min = "2000-01-01", max = "2019-12-31"),
  verbatimTextOutput(outputId = "date_output2")
)

# Create the server
server <- function(session = session, input = input, output = output){
  # Update the date selection in date_input2
  observe({
    updateDateRangeInput(session = session, inputId = "date_input2", label = "Select Date Range 1",
                    start = input$date_input1[[1]], end = input$date_input1[[2]],
                    min = "2000-01-01", max = "2019-12-31")
  })
  
  # Print the selected date
  output$date_output1 <- renderText({
    paste(input$date_input1[[1]], input$date_input1[[2]], sep = " - ")
  })
  
  output$date_output2 <- renderText({
    paste(input$date_input2[[1]], input$date_input2[[2]], sep = " - ")
  })
}

# Run the application 
shinyApp(ui = ui, server = server)
1 Answers

Add this line before the updateDateRangeInput call

req(input$date_input1[[1]],input$date_input1[[2]])

The problem is that when you are editing by hand, for a time the date is not properly formed and is permanently breaking the second date input for some reason. The req() call just insists that there are proper values in there before updating the second date input.

Related