0

I have a Shiny app that wrangles a large csv file. Currently the user can select a facility_id number from a drop down menu to get a specific plot, see https://r.timetochange.today/shiny/Annual_Emissions2/. I would like to pass this id with a URL parameter like /?selected_facilities=1010040 so I can embed the plots in another website.

I have taken the code from How do you pass parameters to a shiny app via URL and tried to use it to update my selectInput() value in the server section of the Shiny app, but I don't really understand how the UI part is constructed so I am not getting it right. Any help would really be appreciated! Here is the relevant code:

#### shiny UI ####
facilities <- unique(ghg_emissions$facility_id)

ui <- fluidPage(
  titlePanel("Annual Greenhouse Gas Emissions"),
  sidebarLayout(
    sidebarPanel(
      selectInput("selected_facility", 
                  "Select facility", 
                  choices = facilities) # select input gives the drop down menu to select facilities
    ),
    mainPanel(
      plotlyOutput("facility_plot")
    )
  )
)

#### shiny server ####
server <- function(input, output, session) {
  # Here you read the URL parameter from session$clientData$url_search
  observe({
    query <- parseQueryString(session$clientData$url_search)
    if (!is.null(query[['selected_facility']])) {
      updateSelectInput(session, "selected_facility", value = query[['selected_facility']])
    }
  })

1 Answer 1

1

Your UI is good, the issue with the updateSelectInput, use selected rather than value and include choices.

Minimal working example:

library(shiny)

facilities <- seq(1:5)

ui <- fluidPage(
    
    selectInput("selected_facility", "Select facility", choices = facilities)
    
)

server <- function(input, output, session) {
    
    observe({
       
        #Get URL query
        query <- parseQueryString(session$clientData$url_search)
        
        #Ignore if the URL query is null
        if (!is.null(query[['selected_facility']])) {

            #Update the select input
            updateSelectInput(session, "selected_facility", selected  = query[['selected_facility']], choices = facilities)
            
        }
        
    })
    
}

shinyApp(ui, server)

To test, run your shiny app, click 'Open in Browser' and append your query to the URL, e.g.

127.0.0.1:6054/?selected_facility=4
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.