Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
591 views
in Technique[技术] by (71.8m points)

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...