17  Print debugging

Published

2024-09-03

Warning

The contents for section are under development. Thank you for your patience.

I’ve created the shinypak R package In an effort to make each section accessible and easy to follow:

Install shinypak using pak (or remotes):

# install.packages('pak')
pak::pak('mjfrigaard/shinypak')

Review the chapters in each section:

library(shinypak)
list_apps(regex = 'debug')
## # A tibble: 5 × 2
##   branch                   last_updated       
##   <chr>                    <dttm>             
## 1 15_debug-util-funs       2024-09-04 10:06:57
## 2 25.0_debug-error         2024-02-13 04:29:39
## 3 25.1_debug-selected_vars 2024-01-15 10:29:25
## 4 25.2_debug-var_inputs    2024-01-15 10:25:12
## 5 25.4_debug-print         2024-01-15 10:04:21

Launch the app:

launch(app = "23.1_debug-error")

Download the app:

get_app(app = "23.1_debug-error")

Launch app with the shinypak package:

launch('25.4_debug-print')

One of the best tried and tested methods of debugging is simply adding a cat() or print() call somewhere in your code to print variables or objects to the R console. This is a basic but effective way to track variable changes.

We can do something similar in Shiny applications by combining verbatimTextOutput(), renderPrint(), and reactiveValuesToList():

In mod_var_input:

    code("module reactive values"),
    verbatimTextOutput(outputId = ns("mod_vals"))
  )
1
Optional label
2
Include the ns() for the inputId
  output$mod_vals <- renderPrint({
    lobstr::tree(
      reactiveValuesToList(
        x = input,
        all.names = TRUE
      )
    )
  })
1
Collect reactive values in module
2
Print these values to the UI
3
Include all reactive objects

Load the package and run the app:


Ctrl/Cmd + Shift + L

ℹ Loading sap
launch_app(options = list(test.mode = FALSE), run = 'p')
(a) ‘Print’ in launch_app()
Figure 17.1: reactiveValuesToList() printed from mod_var_inputs

Now we can see the reactive values from our module in the application sidebar!

We can also use this ‘print’ method to explore reactive values at various locations in our application. For example, if we wanted to print the reactive values for multiple modules in an app, we can use these methods in the top level movies_ui() and movies_server() functions.

In the bslib portion of movies_ui():

In movies_server():

Load the package and run the app:


Ctrl/Cmd + Shift + L

ℹ Loading sap
launch_app(options = list(test.mode = FALSE), 
  run = 'p', bslib = TRUE)
(a) ‘Print’ in launch_app(bslib = TRUE)
Figure 17.2: reactiveValuesToList() printed from movies_ui() and movies_server()

Here we can see both levels of reactive values (from the module and the UI/server functions). The handy thing about this method is that the values change when we interact with the application:

(a) Changing values in launch_app(bslib = TRUE)
Figure 17.3: y and vars-y both update when the UI inputs change