Search code examples
rshinyselectinput

R Shiny - What is the problem with my observe function ({UpdateSelectInput})?


I've looked on similar posts for my problem, but nothing is helping and I'm running out of patience.

I have a very simple app, where I'm trying to find all counties within a selected US state. I'm using SelectInput in the UI for users to select what state they want, and an UpdateSelectInput in the server so users can select what county they want from their state selection.

This is what my simplified data looks like:

**STATE_NAME      NAMELSAD**
Alabama            Clay County  
Alabama            Marengo County
Arkansas           Scott County

My code looks like this:

global.r

library(shiny)
library(leaflet)
library(sp)
library(rgdal)
library(htmltools)
library(DT)
library(ggplot2)
library(shinythemes)

path <- "C:/Users/user/Desktop/Countyapp/Countyapp/test_covid/"
setwd(path)

counties <- read.csv("us_counties1.csv")

UI.r

ui <- fluidPage(
        selectInput(inputId = "selectstate", label = "Select State", choices = (counties$STATE_NAME)),
        selectInput(inputId = "selectcounty", label =  "Select County", choices = NULL)
)

And finally, the server.R

server <- function(session, input, output) {

    observe({
        updateSelectInput(session, "selectcounty", "Select County", 
                          choices = counties$NAMELSAD[counties$STATE_NAME==input$STATE_NAME])
    })

}

shinyApp(ui = ui, server = [enter image description here][1]server) 

Basically, my first SelectInput works, you can choose whatever state you want. But the second selector is blank! Whyyyyyyy. There is something wrong with my observe function, but I've been sitting here forever and am out of possible solutions. Please help if you can! Thank you!


Solution

  • Gosh, I'm stupid.

    It's because I named the input wrong in my observe event.

    got it working. Answer:

      observe({
            updateSelectInput(session, "selectcounty", "Select County", 
                              choices = counties$NAMELSAD[counties$STATE_NAME==input$selectstate])
        })