11.4 Updating the URL

It is probably more convenient to have the URL just update itself whenever inputs change instead of having the user press button each time a state must be captured.

This can be accomplished by wrapping information like input values and session information around an observer as such:

observe({
  reactiveValuesToList(input)
  session$doBookmark()
})

The reactiveValuesToList(input) step does what you might expect as.list() to do in base R. It takes the reactive object, input and stores its values and dependencies in a list.

The next step invokes the doBookmark() function from the session object. The session object is an environment that can be used to access information and functionality relating to the session. doBookmark() invokes the onBookmarked() callback function.

FYI: a callback function is:

a function that is passed as an argument to another function, to be “called back” at a later time. A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed.

11.4.1 Storing a richer state

URL bookmarking is simple and works everywhere you may want to deploy your Shiny app however, could become very long if you have a large number of inputs. If this is the case, it may be better to store your state on the server side.

Shiny saves the state of your app in an .rds file on the server and generates a shorter and easier URL. To do this, you can simply change the enableBookmarking argument to be “server” instead of “url”

shinyApp(ui, server, enableBookmarking = "server")

This generates URLs like this: http://127.0.0.1:4087/?_state_id_=0d645f1b28f05c97

The parameter in this instance is the state_id which corresponds to a directory in your working directory - shiny_bookmarks/0d645f1b28f05c97

⚠️ Be sure to have a mechanism to routinely delete these directories. If your app requires bookmarking in a complex state and you do not delete these files, your app is going to take up more disk space and may start to lag. However, when you do delete these files, their corresponding URLs will also stop working. Just be sure to either send updated links to stakeholders or be mindful of the state of your app.