Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store the returned value from a Shiny module in reactiveValues?

Tags:

r

shiny

Version 1 below is a toy module that asks for a user input txt, and return the input to the main Shiny app. The main Shiny app then render the text and output it to the screen.

Here I store the return value of the module in a variable called mytxt and I called it through renderText({ mytxt() }).


However, what I actually want to do is to store the returned value to reactiveValues in the main Shiny app. (It doesn't matter if I output it or not as I want to do further evaluations on that value.) But sadly I found no way in making it works. I'm showing my failed codes in Version 2 below.


Version 1 (Correct)

app.R

library(shiny)
source("module_1.R")

ui <- fluidPage(

  returnUI("returntxt"),
  textOutput("mytxt")

)

server <- function(input, output, session) {

  mytxt <- callModule(returnServer, "returntxt")

  output$mytxt <- renderText({ mytxt() })

}

shinyApp(ui, server)

module_1.R

returnUI = function(id) {
  ns <- NS(id)

  tagList(
    textInput(ns("txt"), "Write something")
  )
}


returnServer = function(input, output, session) {
  mytxt <- reactive({
    input$txt
  })

  return(mytxt)
}

Version 2 (Need help!)

app.R

library(shiny)
source("modules/module_1.R")

ui <- fluidPage(

  returnUI("returntxt"),
  textOutput("mytxt")

)

server <- function(input, output, session) {

  myvals <- reactiveValues(
    txt = NULL
  )

  mytxt <- callModule(returnServer, "returntxt")

  myvals$txt <- isolate(mytxt())

  output$mytxt <- renderText({ myvals$txt })

}

shinyApp(ui, server)

module.R is the same as Version 1.

like image 1000
Cecilia Lee Avatar asked Feb 20 '18 09:02

Cecilia Lee


1 Answers

I just found the answer by returning reactiveValues from the module and use observe :) Woohoo!

app.R

library(shiny)
source("modules/module_1.R")

ui <- fluidPage(

  returnUI("returntxt"),
  textOutput("mytxt")

)

server <- function(input, output, session) {

  myvals <- reactiveValues(
    txt = NULL
  )

  mytxt <- callModule(returnServer, "returntxt")

  observe({ 
    myvals$txt <- mytxt$txt 
    print(myvals$txt)
  })

  output$mytxt <- renderText({ myvals$txt })

}

shinyApp(ui, server)

module_1.R

returnUI = function(id) {
  ns <- NS(id)

  tagList(
    textInput(ns("txt"), "Write something")
  )
}

returnServer = function(input, output, session) {
  myreturn <- reactiveValues()

  observe({ myreturn$txt <- input$txt })

  return(myreturn)
}
like image 189
Cecilia Lee Avatar answered Oct 23 '22 13:10

Cecilia Lee