I'm building a Shiny app that consists of
- A
fileInput
for the user to upload a CSV of transactions - An
actionButton
that lets the user test the app with a pre-built dataset (i.e. without them having to load their own data). - A
verbatimTextOutput
that prints a preview of the dataset they're using and - 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?