Please find the reprex below:
my_react is a reactive element and we want to update based on selectInput.
However, I tried to reassign it to the same reactive element but it gave an error.
Is there a way to reassign the reactive element to itself based on some condition user's select?
library(shiny)
library(tidyverse)
# Module UI to read content
mod_readUI <- function(id) {
ns <- shiny::NS(id)
shiny::tagList(
fileInput(ns("file1"),
h3("Choose xlsx file"),
accept=c(".xlsx")),
actionButton(ns("ref"), "Refresh")
)
}
# Server modules of reading content
mod_read <- function(input, output, session, choice){
dropDown = reactive({
choice()
})
# Uploaded data as reactive element
my_react <- reactive({
req(input$file1) # Ensure file is uploaded
if(!is.null(input$file1)){
my_data <- readxl::read_excel(input$file1$datapath)
my_data
}
else{
my_data <- "nothing" %>% as.data.frame()
my_data
}
})
### Basically, want to update the reactive element ONLY if dropdown == "cyl"
my_react <- reactive({
# browser()
if(dropDown() == "cyl"){
my_react() %>% select(dropDown())
} else{
my_react()
}
})
### In order to pass data as reactive elements to other module:
# Created list
reactive({
# browser()
list("excl" = my_react()#,
#"incl" = my_react_another()
)
})
}
# Module UI to display content
mod_displayUI <- function(id) {
ns <- shiny::NS(id)
shiny::tagList(
DT::dataTableOutput(ns("contents"))
)
}
# Server functions
mod_display <- function(input, output, session, file) {
output$contents <- DT::renderDataTable({
req(file()) # ensures rendertable waits until file is available
DT::datatable(file()$excl,
options = list(pageLength = 7,scrollX = TRUE))
})
}
ui <-
shinydashboard::dashboardPage(
shinydashboard::dashboardHeader(),
shinydashboard::dashboardSidebar(
shinydashboard::sidebarMenu(id = "menu1",
shinydashboard::menuItem('mod1',
tabName = 'mod1',
icon = shiny::icon('file')),
shinydashboard::menuItem('mod2',
tabName = 'mod2',
icon = shiny::icon('file')),
selectInput("sel","Choose",
c("Cylinders" = "cyl",
"Transmission" = "am",
"Gears" = "gear"))
)),
shinydashboard::dashboardBody(
shinydashboard::tabItems(
shinydashboard::tabItem("mod1",
mod_readUI("sidemod1")),
shinydashboard::tabItem("mod2",
mod_displayUI("bodymod2")
)
)))
server <- function(input, output) {
choice <- reactive({
input$sel})
# storing mod_read in a variable
readFile1 <- shiny::callModule(mod_read, "sidemod1", choice)
# passing the output of readFile into mod_display module
displayFile <- shiny::callModule(mod_display, "bodymod2", file = readFile1)
}
shinyApp(ui,server)