Referring to reactive value outside of render() function

Hello everyone,

I encountered a problem while writing a shiny App that I do not find a solution online for.

In the code snippet below, I know that I cannot refer to errors() without an reactive environment. However, if I include length(reactive({errors()[[1]]})) I get an error, whereas if I just use a number instead, the code works just fine. I would be very thankful for any pointers.

The error message is: Error in 1:reactive(length(errors()[[1]])) : NA/NaN argument

Here is a code snippet from the server.R:

lapply(1:length(errors()[[1]]), function(j) {
    output[[paste0('out',j)]] <- renderDataTable({
      datatable(data.table(Kommentar = "", errors()[[1]][[j]]), options = list(
        pageLength = 20,
        lengthMenu = c(5, 20, 50, 200))
      )
    })
  })

1 Like

Hi @Peddapaan! Welcome to Community!

Short answer: Put the lapply inside an observe({ ... }) function.

Looking at the code, my guess is that you're trying to display all of the content of errors()[[1]] in independent tables.

Even though this code is inside your server function, it needs to run inside a reactive environment, such as observe.

observe({
  lapply(1:length(errors()[[1]]), function(j) {
    output[[paste0('out',j)]] <- renderDataTable({
      datatable(data.table(Kommentar = "", errors()[[1]][[j]]), options = list(
        pageLength = 20,
        lengthMenu = c(5, 20, 50, 200))
      )
    })
  })
})

This the code snippet in the observe statement will run every time errors is updated with a new value.

2 Likes

Thank you. It works! :slight_smile:

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.