Ben
Ben

Reputation: 21625

Allow user to load their data via CSV or use a sample dataset

I'm building a Shiny app that consists of

  1. A fileInput for the user to upload a CSV of transactions
  2. An actionButton that lets the user test the app with a pre-built dataset (i.e. without them having to load their own data).
  3. A verbatimTextOutput that prints a preview of the dataset they're using and
  4. Various plot and charts built using their selected dataset

If the user uploads a file, that dataset should become the "master" transactions dataset to feed the rest of the app. If they then click the "load sample data" button, that datset should turn into the "master" transactions dataset. (Extrapolate this idea to multiple alternations between them uploading data and clicking the button)

I can get this to work as follows:

# app.R    

library(data.table)
library(shiny)

# UI
ui <- shinyUI(fluidPage(
  fileInput(inputId='fi_file', label='Choose CSV File', accept=c('text/csv', 'text/comma-separated-values,text/plain', '.csv')),
  actionButton(inputId="ab_loadSampleTransactions", label="Load Sample Transactions"),
  verbatimTextOutput("vto_transactions")
))


# Server
server <- shinyServer(function(input, output) {

  # When the user uploads a file, print it
  observeEvent(input$fi_file, {
    transactions <- read.csv(input$fi_file$datapath)
    output$vto_transactions <- renderPrint(transactions)
  })

  # When the user clicks the button for sample transactions, print them
  observeEvent(input$ab_loadSampleTransactions, {
    transactions <- data.table(ID=c(1,2,3), Amount=c(100, 150, 125))
    output$vto_transactions <- renderPrint(transactions)
  })

  # More logic involving the transactions dataset
  # ...

})

# Run the application 
shinyApp(ui = ui, server = server)

However, this is inefficient because it requires me to load the transactions dataset twice in order to display it and do future logic with it. I think I need to do something reactive here, but I can't figure out how since I have two separate methods for loading the data. Help?

Upvotes: 0

Views: 340

Answers (1)

DeanAttali
DeanAttali

Reputation: 26323

Don't use global variables like the suggestion in the comment says.

Use reactiveValues. It sounds like you don't need this variable to be "global" in the sense that it needs to be shared with the UI and other files -- it just needs to be global within the server, correct? In that case, you can use reactiveValues and those variables can be accessed and set anywhere in your server

Upvotes: 2

Related Questions