Home > Mobile >  How to use inputs values from main file to module file in Shiny
How to use inputs values from main file to module file in Shiny

Time:01-22

I am improving and changing my question.

This code does the following

Once I click on the link's name, its name is sent to the module display inside the h1 tag from the module:

This is my module code:

example_UI <- function(id) {
      ns <- NS(id)
      tagList(    
        htmlOutput(ns('name_from_main'))    
      )
    }

example_Server <- function(id, names) {
      moduleServer(
        id,
        function(input, output, session) {

          output$name_from_main <- renderUI({    
            h1(names())    
          })    
        }
      )
    }

My main app code is this:

ui <- fluidPage(
      names(mtcars)[1:4] %>% map(~ actionLink(label = paste0(.x),
                                         inputId = paste0(.x))),
    example_UI('example')
)

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

  object <- reactive({
            if(input$mpg != 0){

              "MPG"

            }else{
              if(input$hp != 0){

                "HP"

              }else{
                if(input$cyl != 0){
                  "cyl"

                }else{
                    "others"
                }
              }
            }
    })

      example_Server("example", names = object )

}

shinyApp(ui, server)

My problem is that its not complete. Once I click on the links its onl change for the first time. And the others links names are not displayed bellow.

I think the problem is on the object variable.

Any help?

CodePudding user response:

The reason why the name updates only once, has to do with the fact that as soon as the mpg link is pressed once, the associated value to that input will be different to zero for the rest of the apps life.

One way to mitigate this is to have one observer for each link and using a single reactiveVal to store the information of the last link pressed.

server <- function(input, output, session) {
  
  name <- reactiveVal("OTHERS")
  
  observeEvent(input$mpg, {
    name("MPG")
  })
  
  observeEvent(input$cyl, {
    name("CYL")
  })
  
  observeEvent(input$disp, {
    name("DISP")
  })
  
  observeEvent(input$hp, {
    name("HP")
  })
  
  # pass reactiveVal as the names argument
  example_Server("example", names = name)
}

Another alternative is to use another kind of input to capture different values more easily. In this case input$name will contain the last selected value from the inputs.

ui <- fluidPage(
  shinyWidgets::radioGroupButtons(
    inputId    = "name",
    label      = "",
    choices    = names(mtcars)[1:4],
    status     = "primary",
    individual = TRUE
  ),
  example_UI("example")
)

server <- function(input, output, session) {
  example_Server(
    id    = "example",
    names = reactive(toupper(input$name))
  )
}

shinyApp(ui, server)
  • Related