Home > Blockchain >  Shiny conditionalPanel() seemingly evaluating incorrectly. How to make UI hide something based on se
Shiny conditionalPanel() seemingly evaluating incorrectly. How to make UI hide something based on se

Time:08-08

I'm trying to make a simple app that hides information until a user is logged ind:

library(shiny)
library(glue)
library(tidyverse)

server <- function(input, output, session) {
  #check login
  logged_in = eventReactive(input$login, {
    if (input$username == "test" && input$password == "test") {
      return(T)
    } else {
      return(F)
    }
  })
  
  username = reactive(input$username)
  
  output$login_status = logged_in
  
  output$login_status_text = renderText({
    if (logged_in()) {
      return(glue("Logged in as: {username()}"))
    } else {
      return("Not logged in / incorrect login")
    }
  })
  
  output$data = renderDataTable({
    if (logged_in()) {
      y = iris
    } else {
      y = tibble(text = "This should not be seen!")
    }

    y
  })
}

ui <- fluidPage(
  textInput("username", "What's your username?"),
  passwordInput("password", "What's your password?"),
  actionButton("login", "Login!"),
  textOutput("login_status_text"),
  #show secret data if logged in
  conditionalPanel(condition = "output.login_status()", {
    dataTableOutput("data")
  })
)


shinyApp(ui, server)

The issue is that the condition is somehow evaluated as true always. I've tried output.login_status, which is always evaluated as FALSE. How do I make the UI show/hide something based on an output server-side, not input client-side, value?

CodePudding user response:

You have to add this line in the server:

outputOptions(output, "login_status", suspendWhenHidden = FALSE)

Like this:

output$login_status = reactive(logged_in())
outputOptions(output, "login_status", suspendWhenHidden = FALSE)

Furthermore, the condition should be:

condition = "output.login_status"
  • Related