Skip to content

session$clientData$url_hash doesn't update correctly with NavLink() #4

@lgnbhl

Description

@lgnbhl

In some use cases, it is very useful to be able to observe the hash url of the current shiny session. However, it seems that the session$clientData$url_hash object doesn't update correctly when NavLink() is used.

A workaround it to use session$reload() while observing NavLink.inputId() as well as using sometimes tags$a() instead of NavLink().

Below a minimal example of the issue with the workaround (commented):

library(shiny)
library(reactRouter)
library(bslib)

ui <- HashRouter(
  bslib::page(
    reactRouter::Link.shinyInput(
      inputId = "home",
      to = "/", 
      h3("reactRouter with dynamic routes", class = "m-3"),
      style = "text-decoration: none; color: black"
    ),
    Routes(
      Route(
        path = "/", 
        element = div(
          # tags$a() necessary instead of NavLink.shinyInput()
          tags$a(
            href = "#/1", # or "#/1/overview"
            "Project 1"
          ),
          tags$a(
            href = "#/2",
            "Project 2"
          )
        )
      ),
      Route(
        path = "/:id/*", 
        element = div(
          NavLink.shinyInput(
            inputId = "overview",
            to = "overview",
            "Overview"
          ),
          NavLink.shinyInput(
            inputId = "analysis",
            to = "analysis",
            "Analysis"
          ),
          Outlet()
        ),
        reactRouter::Route(
          path = "overview",
          element = uiOutput("uiOverview")
        ),
        reactRouter::Route(
          path = "analysis",
          element = uiOutput("uiAnalysis")
        )
      )
    )
  )
)

server <- function(input, output, session) {
  
  # FIX HERE
  # Necessary to update `url_hash` to get "" (homepage), "1/analysis" and "2/analysis"
  # observeEvent(c(input$home, input$overview, input$analysis), {
  #   session$reload()
  # })
  
  url_hash <- shiny::reactiveVal(value = NA)

  # update reactive values based on url hash
  shiny::observe({
    current_url_hash <- session$clientData$url_hash
    print(current_url_hash)
    url_hash(current_url_hash)
  })
  
  output$uiOverview <- renderUI({
    url_hash()
  })
  output$uiAnalysis <- renderUI({
    url_hash()
  })
}

shinyApp(ui, server)

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    Status

    Done

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions