Search code examples
rshinyshiny-server

Invoke function in shinyServer using reactive


I have a shiny app which calls an external function based on user input. This function updates a data frame based on the input so it can be used to render a plot.

getData function()

getData= function(inpName)
{
   // a piece of code based on inpName
}

shinyUI.R

library(shiny)
shinyUI(fluidPage(
  titlePanel("title"),
  sidebarLayout(
    sidebarPanel(
      textInput("name","Enter a name")),
    mainPanel())
))

shinyServer.R

library(shiny)
shinyServer(function(input,output)
  {
  getData=reactive({getData(input$name) })
})

No matter what I try I just can't seem to get the shinyServer to call the function and update a df. Could someone advise what am doing wrong? Appreciate any help.


Solution

  • You don't want to be overwriting getData in the server function.

    library(shiny)
    getData <- function(inpName) 
        if (inpName %in% names(mtcars)) mtcars[,inpName] else NULL
    
    shinyApp(
        shinyUI(fluidPage(
            titlePanel("title"),
            sidebarLayout(
                sidebarPanel(
                    textInput("name","Enter a name")),
                mainPanel(
                    verbatimTextOutput('tab')
                ))
        )),
        shinyServer(function(input, output, session) {
            ## The first way
            ## dat <- reactive({ getData(input$name) })
    
            ## The other way
            vals <- reactiveValues(dat=NULL)
            observeEvent(input$name, vals$dat <- getData(input$name))
    
            output$tab <- renderPrint({ summary(vals$dat) })
        })
    )